3
 <span class="byline">
 <ul class="foobar"></ul>
 <img alt="" src="resize_image.php?src=images/newsManagement/87600069ef0dffad5fd02f862ea3787b.jpg&w=675&h=675">
 <p style="text-align: justify;">
 <img alt="" src="resize_image.php?src=images/newsManagement/87600069ef0dffad5fd02f862ea3787b.jpg&w=675&h=675">
 <hr>

Hi this is my html. I can fetch all images using DOMDocument but i want to get first images that comes after ul.foobar class. I don't want other images. How can I query for that.

I tried this for all images.

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($url);

//$xpath = new DomXpath($doc);
//$entries = $xpath->query("//div[@id='newsbox']/ul[@class='foobar']");

$elements = $dom->getElementsByTagName('img');
if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>". $element->getAttribute('src'). ": ";
  }
}
user254153
  • 1,855
  • 4
  • 41
  • 84

1 Answers1

0

I think you can use DOMXPath query with this xpath expression:

$image = $xpath->query('//ul[@class="foobar"]/following-sibling::img')->item(0);

This will get the following img siblings for <ul class="foobar"> using following-sibling and then get the first item.

The $image is of type DOMElement.

In this example I've used loadHTML to load the html from a string $source. If you want to load your html from a file, you could for example use loadHTMLFile.

$source = <<<SOURCE
<span class="byline">
 <ul class="foobar"></ul>
 <img alt="" src="resize_image.php?src=images/newsManagement/87600069ef0dffad5fd02f862ea3787b.jpg&w=675&h=675">
 <p style="text-align: justify;">
 <img alt="" src="resize_image.php?src=images/newsManagement/87600069ef0dffad5fd02f862ea3787b.jpg&w=675&h=675">
 <hr>
SOURCE;

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($source);
$xpath = new DomXpath($dom);
$image = $xpath->query('//ul[@class="foobar"]/following-sibling::img')->item(0);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70