xPath insert before and after - With DOM and PHP

Posted by Jens Törnell on Stack Overflow See other posts from Stack Overflow or by Jens Törnell
Published on 2011-01-11T18:04:03Z Indexed on 2011/01/12 4:53 UTC
Read the original article Hit count: 264

Filed under:
|

I need to add a class to a HTML structure.

My class is called "container" and should start right after div/ul/li (the child of ul and its simblings, not grandchilds) and should end right before the closing of the same element.

My whole code looks like this:

<?php
$content = '
    <div class="sidebar-1">
        <ul>
            <li>
                <h4>Title</h4>
                <ul> 
                    <li><a href="http://www.test.com">Test</a></li> 
                    <li><a href="http://www.test.com">Test</a></li> 
                </ul> 
            </li> 
            <li>
                <p>Paragraf</p>
            </li> 
            <li>
                <h4>New title</h4>
                <ul> 
                    <li>Some text</li>
                    <li>Some text åäö</li>
                </ul> 
            </li> 
        </ul>
    </div>
';

$doc = new DOMDocument();
$doc->loadHTML($content);
$x = new DOMXPath($doc);

$start_text = '<div class="container">';
$end_text = '</div>';

foreach($x->query('//div/ul/li') as $anchor)
{
    $anchor->insertBefore(new DOMText($start_text),$anchor->firstChild);
}
echo $doc->saveXML($doc->getElementsByTagName('ul')->item(0));
?>

It works as far as i can add the class opening but not the closing element. I also get strange encoding doing this. I want the output to be the same encoding as the input.

The result should be

    <div class="sidebar-1">
        <ul>
            <li>
                <div class="content">
                    <h4>Title</h4>
                    <ul> 
                        <li><a href="http://www.test.com">Test</a></li> 
                        <li><a href="http://www.test.com">Test</a></li> 
                    </ul>
                </div>
            </li> 
            <li>
                <div class="content">
                    <p>Paragraf</p>
                </div>
            </li> 
            <li>
                <div class="content">
                    <h4>New title</h4>
                    <ul> 
                        <li>Some text</li>
                        <li>Some text åäö</li>
                    </ul> 
                </div>
            </li> 
        </ul>
    </div>

© Stack Overflow or respective owner

Related posts about php

Related posts about dom