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?

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.