Search code examples
phpdomdocumentdomxpath

PHP DOMXPath loop through search and find child div value


I am loading external HTML content into a variable like this:

$content = file_get_contents('http://localhost');

The page has a set of loops of <ul> like this:

<ul class="items-list">
<li>Title1</li>
<li>Description1</li>
<li>Location1</li>
</ul>
<!-- OTHER CONTENT HERE BETWEEN THE UL AND THE PRICE DIV -->
<a href="#">
<div class="item-price">£10</div>
<a/>

<ul class="items-list">
<li>Title2</li>
<li>Description2</li>
<li>Location2</li>
</ul>
<!-- OTHER CONTENT HERE BETWEEN THE UL AND THE PRICE DIV -->
<a href="#">
<div class="item-price">£15</div>
</a>

<ul class="items-list">
<li>Title3</li>
<li>Description3</li>
<li>Location3</li>
</ul>
<!-- OTHER CONTENT HERE BETWEEN THE UL AND THE PRICE DIV -->
<a href="#">
<div class="item-price">£20</div>
</a>

<ul class="items-list">
<li>Title4</li>
<li>Description4</li>
<li>Location4</li>
</ul>
<!-- OTHER CONTENT HERE BETWEEN THE UL AND THE PRICE DIV -->
<a href="#">
<div class="item-price">£25</div>
</a>

I have the following code that uses DOMXPath to search for all the items-list UL's and then I can loop through it and echo it.

$dom = new DomDocument();
$dom->loadHTML($content);
$xpath = new DOMXPath($dom); 
$items = $xpath->query("//ul[@class='items-list']"); 

foreach ($items as $node) { 
  echo $node->textContent;
}

This work's perfectly. However, I need help displaying the price of each one of these loops which comes from the div class called item-price which is after the UL but not immediately after.

How can I do this?


Solution

  • foreach ($items as $node) { 
      echo $node->textContent;
      $div = $xpath->query('.//following::div[@class="item-price"][1]', $node); 
      echo $div[0]->nodeValue ."\n\n";
    }
    

    demo