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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置