donglin317704291 2011-05-10 18:06
浏览 48

使用PHP cURL下载多个图像[重复]

This question already has an answer here:

I want to download images from a web page, for example, www.yahoo.com, and store it in a folder using PHP.

I am getting the page source using file_get_contents() and extracting the img src tag. I am passing this src to cURL code. The code does not give any error, but the images are not getting downloaded. Please check out the code. I am not getting where I am going wrong.

<?php
    $html = file_get_contents('www.yahoo.com');
    $ptn = '/< *img[^>]*src *= *["\']?([^"\']*)/i';
    preg_match_all($ptn, $html, $matches, PREG_PATTERN_ORDER);
    $seq = 1;
    foreach($matches as $img)
    {
        $fp = fopen("root/Images/image_$seq.jpg", 'wb');
        $ch = curl_init ($img);
        curl_setopt($ch,CURLOPT_FILE, $fp);
        curl_setopt($ch,CURLOPT_URL, $img);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $image = curl_exec($ch);
        curl_close($ch);
        fwrite($fp, $image);
        fclose($fp);
        $seq++;
    }
    echo "IMAGES DOWNLOADED";
?>
</div>
  • 写回答

3条回答 默认 最新

  • duandu1966 2011-05-10 18:51
    关注
    • Is $img the full URL of the image?
    • Is the image protected (use referer)?

      $image = false;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_REFERER,$url);
      curl_setopt($ch, CURLOPT_URL, $url );
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 7);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch,CURLOPT_ENCODING,gzip);
      curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
      $image = curl_exec ($ch);
      

    Try debugging first.

    First try it with a single image from Yahoo, http://www.depers.nl/beeld/w100/2011/201105/20110510/anp/sport/img-100511-349.onlinebild.jpg.

    Also, why use file_get_contents and curl? Use curl instead.

    1. Make a function for cURL: function simple_curl ( $url,$binary=false){ set your cURL vars, return curl_exec).
    2. Get yahoo.com: $result = simple_curl($url);
    3. Get links with the pattern (check if the matches contains the full URL ( domain + directory + file ).
    4. Loop each pattern match (don't forget: multi array!! So loop on $matches[1]).
    5. curl binary file and save it: $image = simple_curl($match,true);
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据