从url,PHP下载到服务器中的文件夹

时间:2017-04-23 10:09:24

标签: php file-get-contents file-put-contents

我的数据库中有几个图像链接。 我想将这些文件下载到我的服务器中的文件夹,将图像重命名为0.jpeg,1.jpeg,2.jpeg等。 我只设法插入名称为0.jpeg的1。

$result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  

while ($row2 = $result2->fetch()){
    $arrays = $row2["myfoto"];
    foreach(json_decode($arrays) AS $url){
        //prints correctly all files 
        echo $url;
        file_put_contents('/home/my/public_html/place/fotos/[0].jpeg', 
        file_get_contents($url));
    }
 }

1 个答案:

答案 0 :(得分:2)

您需要使用某种增加的索引,然后才能在文件名中使用

使用当前代码的最简单方法是使用结果数组的索引:

$result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  

while ($row2 = $result2->fetch()){
    $arrays = $row2["myfoto"];
    foreach(json_decode($arrays) AS $key => $url){
        //prints correctly all files 
        echo $url;
        file_put_contents('/home/my/public_html/place/fotos/'. $key . '.jpeg', file_get_contents($url));
    }
}

我首选的代码是:

$result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  

while ($row2 = $result2->fetch()){
    $arrays = json_decode($row2["myfoto"]);
    foreach($arrays AS $key => $url){
        //prints correctly all files 
        echo $url;
        file_put_contents('/home/my/public_html/place/fotos/'. $key . '.jpeg', file_get_contents($url));
    }
}

不太喜欢foreach循环定义中的函数