2012-03-07 56 views
3

我怎樣才能TD值,我有這樣這樣的表:使用DOM和PHP

<table> 
<tr> 
    <td>Values</td> 
    <td>5000</td> 
    <td>6000</td> 
</tr> 
</table> 

我想TD的內容。但我無法管理它。

<?PHP 
$dom = new DOMDocument(); 
$dom->loadHTML("figures.html"); 
$table = $dom->getElementsByTagName('table'); 
$tds=$table->getElementsByTagName('td'); 

foreach ($tds as $t){ 
    echo $t->nodeValue, "\n"; 
} 
?> 
+0

'getElementsByTagName'總是返回'DOMNodeList'所以你必須做'$表 - >項目(0) - >的getElementsByTagName( 'TD')' – Gordon 2012-03-07 10:19:19

回答

6

有多種問題與此代碼:

  1. 要從HTML文件加載,你需要使用DOMDocument::loadHTMLFile(),不loadHTML()爲你做了。使用$dom->loadHTMLFile("figures.html")
  2. 您不能像那樣使用getElementsByTagName()(在$table上)。它只能在DOMDocument上使用。

你可以做這樣的事情:

$dom = new DOMDocument(); 
$dom->loadHTMLFile("figures.html"); 
$tables = $dom->getElementsByTagName('table'); 

// Find the correct <table> element you want, and store it in $table 
// ... 

// Assume you want the first table 
$table = $tables->item(0); 

foreach ($table->childNodes as $td) { 
    if ($td->nodeName == 'td') { 
    echo $td->nodeValue, "\n"; 
    } 
} 

或者,你可以只直接搜索與標籤名td所有元素(雖然我敢肯定,你想要做一個表,具體說。方式

0

應該使用一個for循環中顯示多個td'sid屬性,它使得每個td必須表示在HTML文件中的不同id

例如

for($i=1;$i<=10;$i++){ 
echo "<td id ='id_".$i."'>".$tdvalue."</td>"; 
} 

,然後再次,您可以通過迭代另一個for循環來獲取tdgetElementById

+0

有ID,但​​沒什麼IDS不管怎麼說,我應該使用標籤而不是id。 – mustafa2012-03-07 09:55:37