0

我正在使用 php 从 url 获取图像并将其复制到我的服务器,但得到一个错误,说没有这样的文件

图片示例:

http://www.google.co.in/intl/en_com/images/srpr/logo1w.png

这是我正在使用的解决方案:

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);

我收到以下错误。我做错什么了吗?

fopen(/location/to/save/image.jpg): failed to open stream: No such file or directory
4

3 回答 3

1

✓ 这对我有用。


试试不带/location/to/save/

该文件将保存在您运行脚本的同一文件夹中。

如:

<?php

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("image_google.jpg", "w");
fwrite($fp, $content);
fclose($fp);

?>
于 2013-08-15T03:04:37.030 回答
0

文件夹(/location/to/save 在这里)应该存在。您还需要其中的写入权限。

于 2013-08-14T22:38:58.517 回答
0
function download_image($url,$destination_path = '')
{  
    // CHECKS IF CURL DOES EXISTS. SOMETIMES WEB HOSTING DISABLES FILE GET CONTENTS
    if (function_exists('curl_version'))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

    } else
    {
        $content = file_get_contents($url);
    }
    // CHECKS IF DIRECTORY DOESNT EXISTS AND DESTINATION PATH IS NOT EMPTY
    if(!file_exists($destination_path) && $destination_path != ''){
        mkdir($destination_path, 0755, true);  
    }
    // ATTEMPT TO CREATE THE FILE
    $fp = fopen($destination_path.'/'.date('YmdHis').".jpg", "a+");
    fwrite($fp, $content);
    fclose($fp); 
}

download_image('http://davidwalsh.name/wp-content/themes/jack/images/treehouse-1.png','images');
于 2013-08-14T22:39:25.937 回答