user1807658
user1807658

Reputation: 11

PHP Simple HTML DOM - Top level elements only

I have searched through some other threads here but have not found the perfect solution

if I have the following layout

    <html>
<div>   <---- This one
      <div> text </div>
      <div> text </div>
</div> 
<p> text </p>
 <div>  <---- This one
      <div> text </div>
      <div> text </div>
</div>  
<p> text </p>
</html> 

How would I go about getting only the divs on the top level. (NOTE: the two divs inside is only an exmaple, there could be just one, or could be 5 or 6.

Note: The rest of the code that this ties into is using the Simple html dom, I need this to work with that.

Upvotes: 0

Views: 690

Answers (1)

PeeHaa
PeeHaa

Reputation: 72729

One possibiltity is to use XPath. It will look something like the following:

<?php
$doc = new DOMDocument();
// one of the few cases where you may use error suppression
@$doc->loadHTML($yourHtml);

$xPath = new XPath($doc);
$nodes = $xPath->query('//html/div');

Disclaimer: I haven't tested this, but it should at least get you close

Upvotes: 2

Related Questions