您的位置:首页 > 编程语言 > PHP开发

php下载远程文件(图片)的三种方法

2015-09-07 18:11 986 查看
采集数据过程经常需要下载远程的图片保存到本地,本文向大家p介绍三种php下载远程图片的方法:

以下载http://www.54ux.com/wp-content/themes/d-simple/img/thumbnail.jpg图片为例:


1. 使用file_get_contents 和 file_put_contents 方法下载远程图片:

<?php
function download_remote_file($file_url, $save_to)
{
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
?>


实例:
<?php
download_remote_file('http://www.54ux.com/wp-content/themes/d-simple/img/thumbnail.jpg', realpath("./downloads") . '/file.jpg');
?>


2.使用php CURL 下载远程图片

<?php
function download_remote_file_with_curl($file_url, $save_to)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL,$file_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$file_content = curl_exec($ch);
curl_close($ch);

$downloaded_file = fopen($save_to, 'w');
fwrite($downloaded_file, $file_content);
fclose($downloaded_file);

}
?>


实例:
<?php
download_remote_file_with_curl('http://www.54ux.com/wp-content/themes/d-simple/img/thumbnail.jpg', realpath("./downloads") . '/file.jpg');
?>


3. 使用 fopen 下载远程图片:

<?php
function download_remote_file_with_fopen($file_url, $save_to)
{
$in=    fopen($file_url, "rb");
$out=   fopen($save_to, "wb");

while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}

fclose($in);
fclose($out);
}
?>


实例:
<?php
download_remote_file_with_fopen('http://www.54ux.com/wp-content/themes/d-simple/img/thumbnail.jpg', realpath("./downloads") . '/file.jpg');
?>


转载请注明:wordpress教程网 » php下载远程文件(图片)的三种方法(http://www.54ux.com/a-2455.html)

继续浏览有关的文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: