Sebin P Johnson
Sebin P Johnson

Reputation: 147

How to get the hyperlink from an image when given its url

I was wondering is it possible to get the hyperlink of an image if the image url is given for eg: I have a webpage say (http://www.example.com) with an image for eg :

<a href="http://example.com/12344/623/2"><img id="img" src="http://example.com/623/5602225.jpg" alt="The Image" name="img" height="1140" width="800"></a>

I was thinking is it possible to get this

http://example.com/12344/623/2

when i give

http://example.com/623/5602225.jpg

as an input in php and CURL?

Upvotes: 2

Views: 173

Answers (1)

Steve
Steve

Reputation: 20469

Yes, you need to parse the html.

As you tagged SimpleHtmlDom:

include "simple_html_dom.php";
//example html
$html = '<a href="http://example.com/12344/623/1"><img id="img" src="http://example.com/623/5602224.jpg" alt="The Image" name="img" height="1140" width="800"></a>';
$html .= '<a href="http://example.com/12344/623/2"><img id="img" src="http://example.com/623/5602225.jpg" alt="The Image" name="img" height="1140" width="800"></a>';
$html .= '<a href="http://example.com/12344/623/3"><img id="img" src="http://example.com/623/5602226.jpg" alt="The Image" name="img" height="1140" width="800"></a>';

//the image url to search for
$img = 'http://example.com/623/5602225.jpg';

//Note if you want to get the html from a url and not a string,
// use $som = file_get_html('http://www.example.com/');
$dom = str_get_html($html);
$url = $dom->find('img[src='.$img.']', 0)->parent->href;
//$url equals http://example.com/12344/623/2

Upvotes: 2

Related Questions