0
votes

Using the DOMDocument class, I want to return the div elements as array items

 $str = '
 <div class="outer">outer div text
    <div class="inner">inner div text</div>
 </div>
 ';

 $document = new DOMDocument();


ex:

$item[0] = '<div class="outer">outer div text 
               <div class="inner">inner div text</div> 
           </div>'

$item[1] = '<div class="inner">inner div text</div>'
1
possible duplicate of Text from <p> tag using DOM PhpGordon
The content of the first div is $str and not $item[0].powtac
@powtac: $str contains the whole html content, $item[0] contains only the outer div element.Zebra
Also see Noob Question about DOMDocument for some more information on how DOM works.Gordon
@Gordon: I edited my question, my goal is to return all div instances in my html code.Zebra

1 Answers

-1
votes

Try this, not perfect code but it works.

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadHTML($str);
$entries = ($doc->getElementsByTagName('div'));

foreach($entries as $data) {
    $divs[] = '<div>'.trim($data->nodeValue).'</div>';
}