Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract image url from html page with php

how can I extract the post image from this link using php?

I read that I can't do it with regex.

http://www.huffingtonpost.it/2013/07/03/stupri-piazza-tahrir-durante-proteste-anti-morsi_n_3538921.html?utm_hp_ref=italy

Thank you so much.

like image 444
michele Avatar asked Jul 03 '13 10:07

michele


3 Answers

$content=file_get_contents($url);
if (preg_match("/<img.*src=\"(.*)\".*class=\".*pinit\".*>/", $content, $matches)) 
{
echo "Match was found <br />";
echo $matches[0];
}

$matches[0] will print the whole image tag. And if you want to extract only the URL, then you can use $matches[1] to get the same :)

like image 122
Nidhin Joseph Avatar answered Oct 20 '22 22:10

Nidhin Joseph


You can/must parse your html with DOM, here is example with your case:

$curlResource = curl_init('http://www.huffingtonpost.it/2013/07/03/stupri-piazza-tahrir-durante-proteste-anti-morsi_n_3538921.html?utm_hp_ref=italy');
curl_setopt($curlResource, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlResource, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curlResource, CURLOPT_AUTOREFERER, true);

$page = curl_exec($curlResource);
curl_close($curlResource);


$domDocument = new DOMDocument();
$domDocument->loadHTML($page);

$xpath = new DOMXPath($domDocument);

$urlXpath = $xpath->query("//img[@id='img_caption_3538921']/@src");

$url = $urlXpath->item(0)->nodeValue;

echo $url;

Take your time and learn a little DOM and XPATH it's worth it.

like image 41
Aurimas Ličkus Avatar answered Oct 20 '22 23:10

Aurimas Ličkus


Try This ...

$content=file_get_contents($url);
if (preg_match("/src=[\"\'][^\'\']+[\"\']/", $content, $matches)) 
{
    echo "Match was found <br />";
    echo $matches[0];
}
like image 38
Krishna Avatar answered Oct 20 '22 21:10

Krishna