オプション#1
代わりにバイナリ/生データを選ぶの変数を作成してから書き込む場合は、CURLOPT_FILE
オプションを使用して、ファイルをカールに直接表示してダウンロードすることができます。ここで
は関数である。
// takes URL of image and Path for the image as parameter
function download_image1($image_url, $image_file){
$fp = fopen ($image_file, 'w+'); // open file handle
$ch = curl_init($image_url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
// curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
fclose($fp); // closing file handle
}
そして、ここでは、あなたがそれを呼び出す方法を次のとおりです。
// test the download function
download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");
オプション#2
さて、ダウンロードしたい場合非常に大きなファイルの場合、上記の関数の場合は便利にならない場合があります。今回は、大きなファイルを扱うために以下の関数を使用することができます。また、必要に応じて進行状況を印刷することができます(%
またはその他の形式)。以下の関数は、ダウンロードの進行状況に応じてファイルにデータのチャンクを書き込む関数callback
を使用して実装されています。
// takes URL of image and Path for the image as parameter
function download_image2($image_url){
$ch = curl_init($image_url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
// curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
}
/** callback function for curl */
function curl_callback($ch, $bytes){
global $fp;
$len = fwrite($fp, $bytes);
// if you want, you can use any progress printing here
return $len;
}
そして、ここでは、この関数を呼び出す方法です:Komangの答えの
// test the download function
$image_file = "local_image2.jpg";
$fp = fopen ($image_file, 'w+'); // open file handle
download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
fclose($fp); // closing file handle
ありがとうございます!私はこのことを試し続けて、それがうまくいくかどうかを見ていきます。 – David
うまくコーディングされたWebサイトがユーザーエージェントを探すことに注意してください。すべてのブラウザ、タブレット、または携帯電話には常にユーザーエージェントが用意されています。それでもなお画像を取得できない場合、おそらくユーザエージェントの検出のために、これを追加してください... 'curl_setopt($ ch、CURLOPT_USERAGENT、 'MyImage Collector + http://www.yourdomainname/mybot.html'); 'curl_setopt($ ch、CURLOPT_USERAGENT、 'Mozilla/5.0(Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13)Gecko/20080311 Firefox/2.0.0.13');' – bbullis
このような画像を保存する際にファイルサイズの制限はありますか? PHP設定のファイルアップロード制限がこれに影響しますか? – Foreever