michele
michele

Reputation: 26598

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.

Upvotes: 6

Views: 6614

Answers (3)

Krishna
Krishna

Reputation: 381

Try This ...

$content=file_get_contents($url);
if (preg_match("/src=[\"\'][^\'\']+[\"\']/", $content, $matches)) 
{
    echo "Match was found <br />";
    echo $matches[0];
}

Upvotes: 1

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

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.

Upvotes: 2

Nidhin Joseph
Nidhin Joseph

Reputation: 1481

$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 :)

Upvotes: 4

Related Questions