PHP简单HTML DOM解析器初学者



你好,我使用以下代码成功地解析了html页面中的一些表:

foreach($html->find('table') as $table) {
echo '<table>';
echo $table->innertext;
echo '</table>';
}

现在我想解析更多的代码,看看下面的源html:

<h5>.....</h5>
<table>.....</table>
<h5>.....</h5>
<table>.....</table>
<h5>.....</h5>
<table>.....</table>

我试过这个代码:

foreach($html->find('h5') as $h5) {
echo '<h5>';
echo $h5->innertext;
echo '</h5>';
}
foreach($html->find('table') as $table) {
echo '<table>';
echo $table->innertext;
echo '</table>';
}

这是输出:

<h5>.....</h5>
<h5>.....</h5>
<h5>.....</h5>
<table>.....</table>
<table>.....</table>
<table>.....</table>

如何保存原始订单?谢谢

您必须一次获取并循环所有节点

foreach($html->find('h5, table') as $node) { // or ->find('*')
echo '<' . $node->tag . '>'; // $node->tag = 'h5' for a h5-element, and so on
echo $node->innertext;
echo '</' . $node->tag . '>';
}

感谢我能够使用以下代码添加类:

foreach($html->find('h5, .table') as $node) {
echo '<' . $node->tag . ' class="myclass">';
echo $node->innertext;
echo '</' . $node->tag . '>';

最新更新