0

I want to parse image from a website and output into php file. I'm getting element by class and now i want to get it attribute src and then to print out the image. How can i achieve it?

$htmlDoc = new DOMDocument();
$htmlDoc->loadHTML($result);

$simpleHtml = simplexml_import_dom($htmlDoc);
$image = $simpleHtml->xpath('//img[@class^="pdt-thumbnail-image"]@src');

foreach($image as $img) {
    echo '<img =src"'.$img[0].'">';
}

HTML Structure

<img role="presentation" class="pdt-thumbnail-image is-active lazy-image is-loaded" data-reactid="174" src="https://d2xngy2dw7hums.cloudfront.net/media/photos/products/2016/08/04/samsung_car_fast_charger_1470291965_408c5b7a.jpg">

Output error:

Invalid argument supplied for foreach()
IMSoP
  • 89,526
  • 13
  • 117
  • 169
Andrew
  • 1,507
  • 1
  • 22
  • 42

1 Answers1

0

If you check your error logs, or turn on display_errors on your development environment, you should see a warning that the XPath evaluation failed, because [@class^="pdt-thumbnail-image"] is not valid XPath. (Note that the XML library PHP uses only supports XPath 1.0.)

Instead, you should use the starts-with function, or probably more useful for matching a class, the contains function:

 $simpleHtml->xpath('//img[contains(@class, "pdt-thumbnail-image")]/@src');

Note also that you were missing the / in /@src.

IMSoP
  • 89,526
  • 13
  • 117
  • 169