如何在csv中保存列表图像URL中的图像

时间:2016-02-01 10:45:57

标签: php image file csv

我希望在下载到csv后将图像从url保存到我的目录及其图像名称。

我编写了以下存储图像的代码。但它没有按我的意愿工作。 在下面的代码$ img是变量,它从csv获取url。

假设我在csv中有1000多个产品,并且每个产品都有图像网址 www.example.com/images/image1.jpg

所以我想将这个图像下载到我的本地目录/服务器目录,并在下载到csv文件后存储其图像名称,这样我就可以只将图像名称添加到数据库表中。

set_time_limit(1000);    
		while($url = $response->fetch()) {
		    $my_image = file_get_contents($img);
		    $my_file = fopen('/csvfiles/','w+'); 
		    fwrite($my_file,$my_image);
		    fclose($my_file);
		  }

我在其他类似问题上找到的一些解决方案是

	$file = file_get_contents($img);
	file_put_contents("/csvfiles/Tmpfile.zip", fopen($img, 'r'));

但它不适合我的情况或不工作。

任何帮助将不胜感激。

编辑新内容 - 标记为重复我想在此处添加更多信息 -

由于我拥有csv格式的所有产品信息,并且在导入产品时我还想从其网址下载图像。并且无法手动下载1000+产品图像。我检查了上述解决方案但不适用于这种情况。如上述解决方案,他们只从特定页面下载图像并直接重命名。所以这是不同的场景。

新代码 - 我也试过这段代码仍无法正常工作

$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
$fp = fopen("/csvfiles/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);

3 个答案:

答案 0 :(得分:0)

尝试使用以下代码。

set_time_limit(1000);
while ($url = $response->fetch()) {
    $my_image = file_get_contents($img);
    // check stricly that you have content of image
    if ($my_image !== false) {
        // download the image and store in the database.
        $my_file = fopen('/csvfiles/', 'w+');
        fwrite($my_file, $my_image);
        fclose($my_file);
    }
}

答案 1 :(得分:0)

您还需要一个文件名,而不仅仅是一个目录:

// download the inage from the internet:
$my_image = file_get_contents($url);

// get filename from url:
$filename = basename($url);

$path = '/csvfiles/' . $filename;

// save image to that file:
$my_file = fopen($path,'w+');
fwrite($my_file, $my_image);
fclose($my_file);

// save $filename to DB

答案 2 :(得分:0)

嗨,下面的代码对我有用..希望它会帮助别人..

感谢@Gavriel和@Alankar

if(!empty($img)){
    $my_image = file_get_contents($img);
    file_get_contents(filename)

    $filename = $data[0] . ".jpg";
     echo $filename. "\n";
    if(!file_exists($filename))
        {
            $my_file = fopen($filename,'w+');
            file_put_contents($filename, $my_image);
            echo $filename . "\n";

        }
    }
    $image = "/uploads/" . $filename;
    echo $image . "\n";

此处$img存储图片的网址。这是从csv文件中获取的。

此处data[0]是csv列,用于唯一地存储图像名称。所以我们可以使用file_exists();否则每当我再次运行我的脚本时它会再次存储图像并以随机临时名称存储它。

相关问题