2014-04-12 52 views
1

嗨,我有一個包含行和列的表。xmlDom調用一個非對象的成員函數項()

<table> 
    <tr> 
    <td style="font-size:14px"></td> 
    </tr> 
    <tr> 
    <td background="image.jpg"></td> 
    </tr> 
</table> 
使用此代碼來獲取所有的標記名稱的元素

和IM td

$td= $xmlDoc->getElementsByTagName('td'); 

然後環路,通過這個代碼來獲取每個td標籤

for($i = 0; $i<$td->length; $x++){ 
    print_r($td->item($i)); 
} 

問題是當td標記內有style屬性,我收到此錯誤 Fatal error: Call to a member function item() on a non-object。但是,如果我刪除td標記內的style屬性,它將起作用。

所以這一個工程:

<table> 
    <tr> 
    <td></td> 
    </tr> 
    <tr> 
    <td background="image.jpg"></td> 
    </tr> 
</table> 

而這其中並不

<table> 
    <tr> 
    <td style="font-size:14px;"></td> 
    </tr> 
    <tr> 
    <td background="image.jpg"></td> 
    </tr> 
</table> 

我的目標是進入td標籤內的background屬性。

回答

1

使用foreach使生活更容易

foreach ($dom->getElementsByTagName('td') as $tag) { 
    if ($tag->getAttribute('background')) { 
     echo $tag->getAttribute('background'); //"prints" image.jpg 
    } 
} 

Working Demo

+0

好會嘗試修改我的代碼,看看它是否工作。 – Kiel

+0

我放的代碼確實是一個工作的代碼:) –

+1

哈哈是的,我相信你! – Kiel

相關問題