1

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';

I need to wrap h tags with div. Parent-child relationship is like h1->h2->h3 and so on. So, I need to wrap div according to it

$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();

Something is going wrong in my code,When I try to execute it keeps on loading not delivering the output and also I'm not sure whether this code will get my expected output as follows

<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>
9
  • 1
    have you done any debugging? What are the results? Commented May 29, 2015 at 12:01
  • No, I haven't done debugging. I want to know whether this code is correct to get my expected output Commented May 29, 2015 at 12:03
  • it is not correct, if you want to know exactly that :) Commented May 29, 2015 at 12:06
  • Ya I want to know that too @Sergei Kovalenko Commented May 29, 2015 at 12:14
  • you really want not just add a child but convert plain to tree structure. it is more difficult task Commented May 29, 2015 at 12:22

1 Answer 1

2

The problems lies here:

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

You are adding new items each time, then the result is an endless loop. You can solve this way:

for ($i = 0, $count = $elements->length; $i < $count; $i++) {     
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively $elements->length could be assigned to a variable outside the loop: $iNumElements = $elements->length; for($i=0; $i<$iNumElements; $i++) { ... }
And one more query, The result is appending at the end of html not replacing the existing html in the place of h tags

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.