使用php从网页下载图像

时间:2012-09-16 00:44:59

标签: php

我正在尝试创建一个PHP函数,从您作为参数放入的网页下载图像。然而,网页本身虽然是一种图库,其中只有非常小的图像缩略图版本,每个版本都直接链接到我想要下载到本地计算机的较大的完整jpeg图像。因此,图像不会直接从我放入函数的网页本身下载,而是从网页上这些jpeg图像文件的各个链接下载。

例如:

www.somesite.com/galleryfullofimages/

是图片库的位置,

然后我想要的图库中的每个jpeg图像文件都位于:

www.somesite.com/galleryfullofimages/images/01.jpg
www.somesite.com/galleryfullofimages/images/02.jpg
www.somesite.com/galleryfullofimages/images/03.jpg

到目前为止,我一直尝试做的是使用file_get_contents函数将网页的完整html作为字符串,然后尝试隔离内部的所有<a href="images/01.jpg">元素引号并将它们放在数组中。然后使用此数组来定位每个图像并使用循环下载它们。

这是我到目前为止所做的:

<?php

$link = "http://www.somesite.com/galleryfullofimages/";
$contents = file_get_contents($link);

$results = preg_split('/<a href="[^"]*"/', $contents);

?>

但我现在陷入困境。我也是正则表达式的新手,你可以看到我尝试使用它。如何隔离每个图像链接然后下载图像?或者有更好的方法完成这项工作吗?我还读过有关使用cURL的内容。但我似乎也无法实现。

我希望这一切都有道理。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

这通常被称为“抓取”网站。您已经在检索页面的标记,因此您将有一个良好的开端。

以下是您需要做的事情:

<?php
// Load the retrieved markup into a DOM object using PHP's
// DOMDocument::loadHTML method.
    $docObj = new DOMDocument();
    $docObj->loadHTML($contents);

// Create a XPath object.
    $xpathObj = new DOMXpath($docObj);

// Query for all a tags. You can get very creative here, depending on your
// understanding of XPath. For example, you could change the query to just
// return the href attribute directly. This code returns all anchor tags in
// the page, if the href attribute ends in ".jpg".
    $elements = $xpathObj->query('//a[ends-with(@href,".jpg")]');

// Process the discovered image URL's. You could use cURL for this,
// or file_get_contents again (since your host has allow_url_fopen enabled)
// to fetch the image directly and then store it locally.
    foreach ($elements as $domNode)
    {
        $url = $domNode->getAttribute('href');
    }
?>

DOMDocument::loadHTML
XPath
XPath::query
allow_url_fopen

相关问题