我的DOM解析器php代码有什么问题?

时间:2015-05-29 11:56:11

标签: php html dom html-parsing

HTML

$html='<h1>some text<h1>
sometext
<h2>some text</h2>
sometext
<h1>some text<h1>
sometext
<h2>some text</h2>
sometext
<h3>some text</h3>
sometext';

我需要用h打包div个标签。亲子关系类似于h1-> h2-> h3,依此类推。所以,我需要根据它包装div

$dom = new DOMDocument();
$dom->loadHTML($html);
$elements = $dom->getElementsByTagName('*');

        for ($i = 0; $i < $elements->length; $i++) {            
        $element = $elements->item($i);
        if ($element->tagName == 'h1'){ 
           $wrap1 = $dom->createElement('div');
           $wrap1->setAttribute('class', 'sect1');

            $wrap1->appendChild($element);
            $dom->appendChild($wrap1);
        }
        if ($element->tagName == 'h2'){ 
           $wrap2 = $dom->createElement('div');
           $wrap2->setAttribute('class', 'sect2');

            $wrap2->appendChild($element);
            $wrap1->appendChild($wrap2);
            $dom->appendChild($wrap1);
        }
    }     

echo $dom->saveHTML();

我的代码中出现了问题,当我尝试执行时,它继续加载而不提供输出,而且我不确定此代码是否会获得我预期的输出如下

<div class="sect1">
<h1>some text<h1>
sometext
<div class="sect2">
<h2>some text</h2>
sometext
</div>
</div>
<div class="sect1">
<h1>some text<h1>
sometext
<div class="sect2">
<h2>some text</h2>
sometext
<div class="sect3">
<h3>some text</h3>
 sometext
</div>
</div>
</div>

1 个答案:

答案 0 :(得分:2)

问题在于:

for ($i = 0; $i < $elements->length; $i++) { 
------------------^^^^^^^^^^^^^^^^^^

您每次都要添加新项目,然后结果是无限循环。你可以这样解决:

for ($i = 0, $count = $elements->length; $i < $count; $i++) {