且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用dom和php获取td值

更新时间:2023-09-03 13:26:34

此代码有多个问题:


  1. 要从HTML文件加载,您需要使用 DOMDocument :: loadHTMLFile()不如你所做的那样 loadHTML()使用 $ dom-> loadHTMLFile(figures.html)

  2. 您不能使用 ($ code> $ table )上的 DOMNodeList 中的getElementsByTagName()它只能在 DOMDocument 中使用。

  1. To load from an HTML file, you need to use DOMDocument::loadHTMLFile(), not loadHTML() as you have done. Use $dom->loadHTMLFile("figures.html").
  2. You can't use getElementsByTagName() on a DOMNodeList as you have done (on $table). It can only be used on a DOMDocument.

你可以做一些类似这个:

You could do something like this:

$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 (虽然我确信你想以表格的方式这样做。

Alternatively, you could just directly search for all elements with tag name td (though I'm sure you want to do that in a table-specific manner.