【问题标题】:How to extract image from website with simple-html-dom? [closed]如何使用 simple-html-dom 从网站中提取图像? [关闭]
【发布时间】:2014-11-22 08:09:21
【问题描述】:

如何从网站中提取图像并使用 simple-html-dom 将它们下载到本地文件中以从文件中加载它们以避免每次都从原始文件中加载图像网站。

include ('simple_html_dom.php');

$html = file_get_html('http://www.caradisiac.com/');
    foreach( $html->find('.featured img') as $image ){
        echo $image->src;
        echo "<br>";
    }

请帮帮我!!

【问题讨论】:

  • 请贴出你目前整理的代码——Stack Overflow 用于解决特定的编程问题;它不是编码服务。你搜索过类似的问题吗?

标签: php image parsing html-parsing simple-html-dom


【解决方案1】:

0 - 请确保您已阅读 PHP manual 以了解 PHP 拥有的所有令人惊叹的内置函数。

1 - 为图像建立一个本地路径,您可以使用preg_replace 来清理 URL

2 - 检查图像尚未使用file_exists 下载,如果是,则加载它;否则下载它

3 - 使用file_get_contents 来检索图像(cURL 会更重)

4 - 使用file_put_contents将其保存到本地文件

foreach( $html->find('.featured img') as $image )
{
    $imageSrc = $image->src;
    $imageUri = $this->rel2abs($imageSrc, $sourceURI);
    $imageLocalPath = 'getImages/'.preg_replace('/[^a-z0-9-.]/i', '-', $imageUri);

    if (!file_exists($imageLocalPath))
    {
        $imageData = file_get_contents($imageUri, false, $streamContext);
        file_put_contents($imageLocalPath, $imageData);
    }
    else
        $imageData = file_get_contents($imageLocalPath);
}

注意事项:

  • 您需要 rel2abs 来解析相对 URI,或任何适当的 pecl 扩展。
  • getImages/ 会将所有图片放在一个子文件夹中:您需要手动创建该子文件夹,或者在 PHP 代码中检查它的存在并在需要时创建它
  • $imageData 包含图像的原始数据,您可以使用imagecreatefromstring 来加载相应的Gd 图像。
  • 请注意:您正在从远程网页下载内容,因此您必须充分信任它。可以在html页面中添加&lt;div class="featured"&gt;&lt;img src="http://evil.com/your-heart-will-bleed.php"/&gt;&lt;/div&gt;这样的标签,恶意的php文件就会被下载。最糟糕的是,它可能通过访问您的网站http://mywebsite.com/getImages/your-heart-will-bleed.php 来执行。

【讨论】:

  • 你从哪里得到 $sourceURI?
  • $sourceURI 是您正在调用的网页 URI(此处为 http://www.caradisiac.com/)。这是必需的,因为 $image-&gt;src 可以是相对的(而在这里,您需要一个绝对 URI 来调用 file_get_contents)。
猜你喜欢
  • 2018-05-23
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多