2009-10-17 148 views
0

我解析從我已經在PHP轉換成一個DOMDocument的API的XML文件。這主要是不錯,但有一個問題我已經是當我這樣做:DOM文檔解析(PHP)

$feeditem->getElementsByTagName('extra'); 

爲FORALL statment的部分和元素的額外不,我在FORALL條件迭代通過再feeditems的一個存在我收到一個錯誤。

我嘗試這樣做:

if (!empty($feeditem->getElementsByTagName('extra'))){ 
$extratag = $feeditem->getElementsByTagName('extra'); 
    $extraname = $extratag->item(0)->getAttribute('name'); 
echo $extraname 
    } 

但我得到的錯誤

getAttribute() on a non-object 

注:當「額外」的元素包含在每feeditem然後代碼運行完美。只是當其中一個供稿項目不包含「額外」元素時,我會收到錯誤消息。

+0

對不起,我的意思是在第四行foreach語句有 –

+0

可以更新(編輯),您的文章,以反映正確的代碼 –

回答

2

嘗試做使用length財產DOMNodeList

$nodes = $feeditem->getElementsByTagName('extra'); 
if ($nodes->length > 0) { 
    $extraname = $extratag->item(0)->getAttribute('name'); 
} 
+0

你真的不需要'> 0'檢查,但這會做你想做的。 –

+0

非常感謝! 被卡住它,因爲昨天! 作品! –

+0

@meder你KHOW爲什麼有時我得到非對象錯誤,但對象存在於XML? http://stackoverflow.com/questions/18096972/how-to-parse-xml-with-php-domdocument-and-be-sure-to-get-objects/18097678?noredirect=1#18097678 – Pooya