2013-02-13 176 views
0

我正在从数组中提取数据,以便将其写入文件供以后使用。如何将提取的数据从数组写入文件

提取工作正常,print_r语句的结果为我提供了所需的数据。但是,输出到文件的数据只能获取提取数据的最后一个值。

我错过了什么?我试过爆炸,将print_r的结果保存为一个字符串,尝试输出缓冲start_ob()而没有结果。

$url = "http://api.discogs.com/users/xxxxxx/collection/folders/0/releases?per_page=100&page=1"; 
    $json = json_decode(file_get_contents($url)); 


// Scan through outer loop 
    foreach ($json as $inner) { 

// scan through inner loop 
     foreach ($inner as $value) { 
//get thumb url 
     $thumb = $value->basic_information->thumb; 
//Remove -150 from thumb url to gain full image url 
      $image = str_replace("-150","",($thumb)); 

// Write it to file 
    file_put_contents("file.txt",$image); 
    print_r($image); 

    } 
    } 

回答

0

您可以用提取的最后一个数据反复重写文件。所以哟需要将数据追加到图像变量,只有最后你需要把它放在磁盘上。

$url = "http://api.discogs.com/users/xxxxxx/collection/folders/0/releases?per_page=100&page=1"; 
    $json = json_decode(file_get_contents($url)); 


// Scan through outer loop 
    foreach ($json as $inner) { 

// scan through inner loop 
     foreach ($inner as $value) { 
//get thumb url 
     $thumb = $value->basic_information->thumb;   
//Remove -150 from thumb url to gain full image url 
// and append it to image 
      $image .= str_replace("-150","",($thumb)); 
// you can add ."\n" to add new line, like: 
//$image .= str_replace("-150","",($thumb))."\n"; 
// Write it to file  

    } 
    } 

    file_put_contents("file.txt",$image); 
    print_r($image); 
+0

没有看到,感谢一百万人为我指出这一点,现在我可以继续我的项目。 – Pimzel 2013-02-14 13:42:24

0

file_put_contents()手册

http://www.php.net/manual/en/function.file-put-contents.php

此功能是相同的主叫fopen()fwrite()fclose()依次将数据写入到文件中。

如果文件名不存在,则创建该文件。否则,现有文件将被覆盖,除非设置了FILE_APPEND标志。

所以,你可以使用标志FILE_APPEND在现有的代码停在每次写重写文件,或积累串写一次像之前的评论者说(他们的方式是更快,更好)