Jump to content

Getting image with its link by DomDocument


etrader

Recommended Posts

It is easy to get image or link by DomDocument, but I did not find a way to get image with its target link. Imagine a html as

<div class=image>
<a href='http://site.com'><img src='imagelink.jpg'></a>
</div>

How to get both the image link and href?

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//div[@class='image']");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);

Now to get the image and its href, we need first getElementsByTagName('a') and getElementsByTagName('img') but they do not work inside foreach.

 

What's your idea?

If I were you I would refrain from using DOMDocument it's very unreliable. Please consider using regex instead which is very precise and powerful for parsing documents for example.

 

This piece of code will return the URLs of all the links in the document that surround an image.

 

preg_match_all('#class="image".*?a href='([^']+).*?img src#s', $html, $imglinks);

foreach ($imglinks[1] as $imglink)
    echo $imglink;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.