如何使用dom和php获取td值


How can I get td values using dom and 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";
}
?>

此代码存在多个问题:

  1. 要从HTML文件加载,需要使用DOMDocument::loadHTMLFile(),而不是像以前那样使用loadHTML()。使用$dom->loadHTMLFile("figures.html")
  2. 不能像在$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;
    }