Arrays 如何将从数组中提取的数据写入文件
我从一个数组中提取数据,目的是将其写入一个文件供以后使用 提取效果很好,print\r语句的结果为我提供了所需的数据。但是,输出到文件的数据只获取提取数据的最后一个值 我错过了什么?我尝试过分解,将打印结果保存为字符串,尝试过输出缓冲start_ob(),但都没有结果Arrays 如何将从数组中提取的数据写入文件,arrays,file,Arrays,File,我从一个数组中提取数据,目的是将其写入一个文件供以后使用 提取效果很好,print\r语句的结果为我提供了所需的数据。但是,输出到文件的数据只获取提取数据的最后一个值 我错过了什么?我尝试过分解,将打印结果保存为字符串,尝试过输出缓冲start_ob(),但都没有结果 $url = "http://api.discogs.com/users/xxxxxx/collection/folders/0/releases?per_page=100&page=1"; $json =
$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);
}
}
用最后提取的数据一次又一次地重写文件。所以,您需要将数据附加到image变量中,最后只需要将其放在磁盘上
$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);
从
文件\u放入内容()
手册
此函数与依次调用fopen()
、fwrite()
和fclose()
将数据写入文件相同
如果文件名不存在,则创建该文件。否则,现有文件将被覆盖,除非设置了file\u APPEND
标志
因此,您可以在现有代码中使用flag
FILE\u APPEND
停止每次写入时重写文件,或者累积字符串并像前面的评论员所说的那样编写一次(他们的方式更快更好)没有看到这一点,非常感谢您向我指出这一点,现在我可以继续我的项目了。