0

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>'
Zebra
  • 3,858
  • 9
  • 39
  • 52
  • possible duplicate of [Text from

    tag using DOM Php](http://stackoverflow.com/questions/4971373/text-from-p-tag-using-dom-php/4971426#4971426)

    – Gordon Mar 29 '11 at 08:42
  • The content of the first div is $str and not $item[0]. – powtac Mar 29 '11 at 08:44
  • @powtac: $str contains the whole html content, $item[0] contains only the outer div element. – Zebra Mar 29 '11 at 08:49
  • 1
    Also see [Noob Question about DOMDocument](http://stackoverflow.com/questions/4979836/noob-question-about-domdocument-in-php/4983721#4983721) for some more information on how DOM works. – Gordon Mar 29 '11 at 08:56
  • @Gordon: I edited my question, my goal is to return all div instances in my html code. – Zebra Mar 29 '11 at 08:59
  • @dany well, i take you know how to put stuff into an array. For the DOM part see both of the linked answers then. It's really just a matter of `getElementsByTagName` and `saveHTML` or `saveXML`. Like I said: Duplicate, hence Closevote :) – Gordon Mar 29 '11 at 09:01
  • possible duplicate of [outerHTML for DOMDocument](http://stackoverflow.com/questions/5404941/php-domdocument-outerhtml-for-element/5404962#5404962) – Gordon Mar 29 '11 at 09:04
  • @Gordon: I know I can return the inner-html of the div layers with the "nodeValue" property, isn't there just a "node" property to return the div layer as a whole? – Zebra Mar 29 '11 at 09:04
  • @dany You are wrong. The nodeValue property will only get the DOMText nodes. It will not include any other elements, hence it's not innerHTML. [There is no innerHTML method](http://stackoverflow.com/questions/2087103/innerhtml-in-phps-domdocument). For the outerHTML see the various linked answers. – Gordon Mar 29 '11 at 09:07

1 Answers1

-1

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>';
}
powtac
  • 40,542
  • 28
  • 115
  • 170
  • there is methods for getting the outerHTML and your solution will not add the attributes, nor will it include the innerHTML. And why is the call to getElementsByTagName in brackets? This solution does not work! – Gordon Mar 29 '11 at 09:10