我正在嘗試將 RSS 提要轉換為 json PHP。我得到了標題、描述等,但我缺少以“itunes”開頭的所有元素。
例如,這沒有顯示在我的 json 中:
<itunes:subtitle>Subtitle text here</itunes:subtitle>
但這些顯示:
<title>Title here</title>
<description>Description here</description>
我認為這與將 XML 轉換為 json 有關,我將此代碼用于:
function Parse($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
誰能幫我理解錯誤發生在哪里?
uj5u.com熱心網友回復:
啊,您正在使用正在執行的字串替換破壞 XML。相反,您需要做的就是將其中的標簽轉換為:在轉換為 JSON 后在 PHP 中有效的東西
所以只要做str_replace()轉換
<itunes:subtitle>Subtitle text here</itunes:subtitle>
到
<itunes_subtitle>Subtitle text here</itunes_subtitle>
這將使這些標簽在轉換為 PHP 資料結構時合法
function Parse($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(':', '_', $fileContents);
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
結果
stdClass Object
(
[@attributes] => stdClass Object
(
[version] => 2.0
[xmlns_itunes] => http_//www.itunes.com/dtds/podcast-1.0.dtd
[xmlns_atom] => http_//www.w3.org/2005/Atom
)
[channel] => stdClass Object
(
[atom_link] => stdClass Object
(
[@attributes] => stdClass Object
(
[href] => https_//feeds.soundcloud.com/users/soundcloud_users_30705140/sounds.rss
[rel] => self
[type] => application/rss xml
)
)
[title] => djsksm
[link] => https_//soundcloud.com/djsksm
[pubDate] => Tue, 18 Dec 2012 01_53_09 0000
[lastBuildDate] => Tue, 18 Dec 2012 01_53_09 0000
[ttl] => 60
[language] => en
[copyright] => All rights reserved
[webMaster] => feeds@soundcloud.com (SoundCloud Feeds)
[description] => Podcast by djsksm
[itunes_subtitle] => Podcast by djsksm
[itunes_owner] => stdClass Object
(
[itunes_name] => djsksm
[itunes_email] => feeds@soundcloud.com
)
[itunes_author] => djsksm
[itunes_explicit] => no
[itunes_image] => stdClass Object
(
[@attributes] => stdClass Object
(
[href] => https_//a1.sndcdn.com/images/default_avatar_original.png
)
)
[image] => stdClass Object
(
[url] => https_//a1.sndcdn.com/images/default_avatar_original.png
[title] => djsksm
[link] => https_//soundcloud.com/djsksm
)
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431213.html
