DOMDocument : Find div, get contents and print without div

I would like to use DOMDocument or another proposed method to do the following in wordpess:

I have this html saved in a variable:

Read More
<div id="gallery-3232" class="gallery gallery-3232">
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
</div>

And I would like to end up with a variable containing that:

<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>
<li><a href=""><img src="" alt="" /></li>

How can I do this but without javascript. With the use of PHP.

Thabnk you

Related posts

Leave a Reply

3 comments

  1. $source = '<div id="gallery-3232" class="gallery gallery-3232">
                <li><a href=""><img src="" alt="" /></li>
                <li><a href=""><img src="" alt="" /></li>
                <li><a href=""><img src="" alt="" /></li>
                <li><a href=""><img src="" alt="" /></li>
                </div>';
    
    $list = new DOMDocument();
    $list->loadHTML($source);
    
    $listItems = $list->getElementsByTagName('li');
    
    $listString = "";
    
    foreach ($listItems as $list) {
        $listString .= $list->C14N();
    }
    
    echo $listString;
    
  2. I just tested this, I think it’s what you require. Basically load the HTML into a DOMDocument, get the element you need by ID and then iterate through its child nodes and output:

    $html = '<div id="gallery-3232" class="gallery gallery-3232">
    <li><a href=""><img src="" alt="" /></li>
    <li><a href=""><img src="" alt="" /></li>
    <li><a href=""><img src="" alt="" /></li>
    <li><a href=""><img src="" alt="" /></li>
    </div>
    ';
    
    $doc = new DomDocument();
    $doc->loadHtml($html);
    $div = $doc->getElementById('gallery-3232');
    $output = '';
    foreach($div->childNodes as $element)
    {
        $output .= $element->ownerDocument->saveHtml($element);
    }
    echo $output;
    
  3. Here’s a quick and dirty way using a regex:

    $string = preg_replace('~</?div[^>]*>~', '', $string);
    

    Note: like I said, this is a quick and dirty way. If you’re sure of your input – use this. However, if you are filtering uncertain input, you’d be better off parsing it properly.