如何在PHP中从动态URL中获取/保存图像

时间:2015-07-07 22:29:25

标签: php curl web-scraping

如何从动态网址中获取/保存图片?

http://www.groove3.com/str/image.php?type=P&id=16470

我正在使用下面的功能,但它不适用于动态网址:

function saveImage($image_url,$save_to){
    if(!file_exists($save_to) && $image_url != "")
    {
        $ch = curl_init($image_url);
        $fp = fopen($save_to, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL,$image_url);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp); 
    }       

}

1 个答案:

答案 0 :(得分:1)

您可以改为使用file_get_contents

$img_content = file_get_contents($image_url);
//Save the file in file system.
$fp = fopen($save_to, "w");
fwrite($fp, $img_content);
fclose($fp);