使用php获取图像src的外部URL

时间:2013-12-13 03:38:49

标签: php

说我有这个链接

$url ="http://www.egyptian-planet.com/news-90.html";

//here get img or <meta property="og:image" from link

如何从链接获取src img或获取<meta property="og:image"(使用PHP)?

任何帮助

1 个答案:

答案 0 :(得分:2)

您可以像这样使用cURL: -

function getHTML($url,$timeout)
{
       $ch = curl_init($url); // initialize curl with given url
       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
       return @curl_exec($ch);
}

$html=getHTML("http://www.egyptian-planet.com/news-90.html",10);

preg_match_all('/<img .*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
    echo $value."<br>";
}

另一种解决方案: -

您还可以使用SimpleHtml库来提取如下图像: -

include_once("simple_html_dom.php");

$html=getHTML("http://www.egyptian-planet.com/news-90.html");

// Find all images on webpage
foreach($html->find("img") as $element)
echo $element->src . '<br>';