如何使用dom和php获取td值

mus*_*afa 3 php dom

我有一张这样的表:

<table>
<tr>
    <td>Values</td>
    <td>5000</td>
    <td>6000</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我想得到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";
}
?>
Run Code Online (Sandbox Code Playgroud)

Mil*_*joo 6

此代码存在多个问题:

  1. 要从HTML文件加载,您需要使用DOMDocument::loadHTMLFile(),而不是loadHTML()像您一样.使用$dom->loadHTMLFile("figures.html").
  2. 你不能像你一样使用getElementsByTagName()on DOMNodeList(on $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";
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以直接搜索具有标记名称的所有元素td(尽管我确定您希望以特定于表的方式执行此操作.