从php中的任何url获取所有图像


Get all images from any url in php?

我的网站上有url的输入类型文本。通过发布这个url字段的值,我想从该特定url中获取所有可能的图像(如果存在),因为这发生在http://facebook.com在更新状态文本区域。那么php中的代码是什么呢?

谢谢。

Facebook有OpenGraph协议。你将在Facebook上链接的许多网站都不会呈现图像。这是因为没有带有og标签的配置。要真正实现抓取图像的任何显著结果,需要大量的代码。

有很多图像并不打算以这种方式使用,例如间隔图像、跟踪图像等。当你从一个网站上提取所有图像标签时,你会得到许多这些图像,它们大多只是空白。

和往常一样,有多种方法可以解决这个问题。它们都是从获取url的来源开始的。cURL是我实现这一目标的首选方法。

从那里你需要解析源中的信息来找到图像的来源。这可以用正则表达式(regex)来完成,或者我喜欢的方法是在PHP中使用DOMDocument类。

关于如何使用DOMDocument类从图像标签中获取源url的简单示例如下:

// Load your HTML result into $response prior to here.
// Additionally, ensure that you have the root url for the
//     page loaded into $base_url.
$document = new DOMDocument();
$document->loadHTML($response);
$images = array();
// For all found img tags
foreach($document->getElementsByTagName('img') as $img) {
    // Extract what we want
    $image = array(
        // Here we take the img tag, get the src attribute
        //     we then run it through a function to ensure that it is not a
        //     relative url.
        // The make_absolute() function will not be covered in this snippet.
        'src' => make_absolute($img->getAttribute('src'), $base_url),
    );
    // Skip images without src
    if( ! $image['src'])
        continue;
    // Add to collection. Use src as key to prevent duplicates.
    $images[$image['src']] = $image;
}