我有一个这样的表:
<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";
}
?>
此代码存在多个问题:
- 要从HTML文件加载,需要使用
DOMDocument::loadHTMLFile()
,而不是像以前那样使用loadHTML()
。使用$dom->loadHTMLFile("figures.html")
- 不能像在
$table
上那样在DOMNodeList
上使用getElementsByTagName()
。它只能在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
的所有元素(尽管我相信您希望以特定于表的方式进行搜索。
您应该使用for循环来显示多个具有id
属性的td's
,这样每个td
在html文件中都必须表示不同的id
例如
for($i=1;$i<=10;$i++){
echo "<td id ='id_".$i."'>".$tdvalue."</td>";
}
然后,您可以通过在getElementById
上迭代另一个for循环来获取td
值
td数据可以在childNodes中找到
$dom = new domDocument;
$dom->loadHTML("your-url");
$tables = $dom->getElementsByTagName('table');
$rows = $tables->getElementsByTagName('tr');
foreach ($rows as $row) {
echo $row->childNodes[0]->nodeValue;
}