2009-10-20 118 views
6

你好,我有XML格式的一系列項目,如該API響應:PHP DOM文檔獲得屬性

<item> 
<title>blah balh</title> 
<pubDate>Tue, 20 Oct 2009 </pubDate> 
<media:file date="today" data="example text string"/> 
</item> 

我想使用的DOMDocument獲取屬性「數據」從標籤「媒體:文件」。我的下面的嘗試不起作用:

$xmldoc = new DOMDocument(); 
$xmldoc->load('api response address'); 
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) { 
$nodes = $feeditem->getElementsByTagName('media:file'); 
$linkthumb = $nodes->item(0)->getAttribute('data'); 
} 

我在做什麼錯?請幫忙。

編輯:我不能因爲某些原因留下評論馬克。我得到錯誤

Call to a member function getAttribute() on a non-object 

當我運行我的代碼。我也試過

$nodes = $feeditem->getElementsByTagNameNS('uri','file'); 
$linkthumb = $nodes->item(0)->getAttribute('data'); 

其中uri是與媒體名稱空間(NS)有關的uri,但又是同樣的問題。

請注意,媒體元素的形式不是我認爲這是問題的一部分,因爲我通常沒有問題解析attibutes。

回答

8

您提供的示例不應產生錯誤。我測試了它和$ linkthumb包含字符串「例如文本字符串」預期

確保媒體命名空間中返回的XML定義,否則DOM文檔時會報錯了。

如果你得到一個特定的錯誤,請編輯您的帖子,包括它

編輯:

試試下面的代碼:

$xmldoc = new DOMDocument(); 
$xmldoc->load('api response address'); 
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) { 
    $nodes = $feeditem->getElementsByTagName('file'); 
    $linkthumb = $nodes->item(0)->getAttribute('data'); 
    echo $linkthumb; 
} 

您可能也想看看SimpleXMLXpath,因爲它使讀取XML比DOMDocument容易得多。

+0

也做到了,額外的代碼。 謝謝! – 2009-10-23 22:25:44

3

另外,

$DOMNode -> attributes -> getNamedItem('MyAttribute') -> value;