我一直在用PHP解析XML時遇到了一個問題,而且沒有真正找到「正確的方式」或者至少是解析XML文件的標準方式。使用PHP解析XML
首先我試圖分析此:
<item>
<title>2884400</title>
<description><![CDATA[ ><img width="126" alt="" src="http://userserve-ak.last.fm/serve/126/27319921.jpg" /> ]]></description>
<link>http://www.last.fm/music/+noredirect/Beatles/+images/27319921</link>
<author>anne710</author>
<pubDate>Tue, 21 Apr 2009 16:12:31 +0000</pubDate>
<guid>http://www.last.fm/music/+noredirect/Beatles/+images/27319921</guid>
<media:content url="http://userserve-ak.last.fm/serve/_/27319921/Beatles+2884400.jpg" fileSize="13065" type="image/jpeg" expression="full" width="126" height="126" />
<media:thumbnail url="http://userserve-ak.last.fm/serve/126/27319921.jpg" type="image/jpeg" width="126" height="126" />
</item>
我使用這個代碼:
$doc = new DOMDocument();
$doc->load('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
);
array_push($arrFeeds, $itemRSS);
}
現在我想要得到的「媒體:內容」和「媒體:縮略圖「網址屬性,我會怎麼做?現在我想我應該使用DOMElement :: getAttribute,但是我沒有設法使它工作:/任何人都可以對此有所瞭解,並且讓我知道這是否是解析XML的好方法?
問候, 沙迪
這整個問題/線程是非常糟糕的。問題是缺乏對名字空間的理解。我建議任何人閱讀這篇文章瞭解XML名稱空間。人們在下面提到了這一點。問題在於media:內容意味着屬於'media'命名空間的'content'標記,而不是默認的命名空間(這就是你要查詢的內容)。 – Jotham 2010-02-11 02:04:18