使用php的简单HTML文件解析器


simple HTML file parser with php

我有一个无法解决的特殊问题。我搜索了每一个教程或表格条目,但没有成功完成我需要做的事情

<html>
 <head>**SOMETHING HERE**</head>
 <body>
  <div>
   <table>
    <thead>
  <tr><th>TEXT/NUM IS HERE</th><th>TEXT/NUM IS HERE</th><th>TEXT/NUM IS HERE</th></tr>
    </thead><tbody>**SOMETHING HERE**</tbody></tfoot>**SOMETHING HERE**</tfoot>
   </table>
  </div>
 </body>
</html>

我需要的是遍历"thead=>tr"标记中的每个标记(th),并将这些"th"标记之间的值记录到一个数组中;

为此,我计划使用DOMDocument和DOMXPath。

我尝试了很多方法来解决这个问题,但在网上找到的最多的方法是:

$file = "index.html";
$dom = new DOMDocument();
$dom->loadHTMLfile($file);
$thead = $dom->getElementsByTagName('thead');
$thead->parentNode;
$th = $thead->getElementsByTagName('th')
echo $th->nodeValue . "'n";

但我仍然有很多错误,找不到方法来做到这一点。有没有任何方法可以完成这个漂亮的结束简单,当然还有父元素中的foreach元素。

谢谢。

使用DOMXPath:

$html = <<<EOL
<html>
    <head>**SOMETHING HERE**</head>
    <body>
        <div>
            <table>
                <thead>
                    <tr>
                        <th>TEXT/NUM IS HERE</th>
                        <th>TEXT/NUM IS HERE</th>
                        <th>TEXT/NUM IS HERE</th>
                    </tr>
                </thead>
                <tbody>**SOMETHING HERE**</tbody>
                <tfoot>**SOMETHING HERE**</tfoot>
            </table>
        </div>
    </body>
</html>
EOL;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//table/thead/tr/th');
$data = array();
foreach ($nodes as $node) {
    $data[] = $node->textContent;
}
print_r($data);
<?php
$html = new file_get_html('file.html');
$th = $html->find('thead th');
$array = array();
foreach($th as $text) 
    $array[] = $th->innertext;
?>

这使用了可以在这里找到的简单HTML Dom解析器。

如果你想让它保持与你现有的风格相同(从而了解你做错了什么),试试这个:

$file = "index.html";
$dom = new DOMDocument();
$dom->loadHTMLfile($file);
$oTHeadList = $dom->getElementsByTagName('thead');
foreach( $oTHeadList as $oThisTHead ){
    $oThList = $oThisTHead->getElementsByTagName('th');
    foreach( $oThList as $oThisTh ) {
        echo $oThisTh->nodeValue . "'n";
    }
}

基本上,"getElementsByTagName"返回的是NodeList而不是Node,因此您必须对它们进行循环才能到达各个节点。

此外,在HTML中,您有一个关闭的tfoot,而不是打开的,如果您使用您提供的HTML文档进行测试,那么head标记中的**SOMETHING HERE**将导致抛出警告(任何其他无效HTML也是如此)。

如果你想在加载时抑制警告,你可以添加一个"@",但在代码周围加太多这个符号不是一个好主意。

@$dom->loadHTMLfile($file);