在Foreach文件中写入在PHP中无法正常工作

时间:2016-12-10 11:59:46

标签: php arrays foreach

我有这样的代码。在PHP中,我想通过foreach循环创建json文件。我的数组如:

Array ( [0] => Array ( [out] => Array ( [id] => 5 [title] => Network [url] => network [label] => forum [tag] => 218 ) [filename] => tags/tag_218 ) [1] => Array ( [out] => Array ( [id] => 6 [title] => Arch [url] => arch [label] => forum [tag] => 218 ) [filename] => tags/tag_218 ) [2] => Array ( [out] => Array ( [id] => 7 [title] => not [url] => not [label] => forum [tag] => 218 )

在我的代码中:

foreach($my_arr as $arr){
    $file_name=$arr['filename']; 
    $response=$arr['out'];
    if(!(file_exists($file_name))){
        $fp = fopen($file_name.'.json', 'w+');
        fwrite($fp, '$response');
        fclose($fp);
    }
    else{
        $fpd = fopen($file_name.'.json', 'a+');
        fwrite($fpd, '$response');
        fclose($fpd);
    }
}

这里创建了文本文件。但只有最后一个数据被追加。为什么呢?

1 个答案:

答案 0 :(得分:0)

尝试使用Fput代替Fwrite,如下所示:

foreach($my_arr as $arr){
$file_name=$arr['filename']; 
$response=$arr['out'];
if(!(file_exists($file_name))){
    $fp = fopen($file_name.'.json', 'w+');
    fput($fp, '$response');
    fclose($fp);
}
else{
    $fpd = fopen($file_name.'.json', 'a+');
    fput($fpd, '$response');
    fclose($fpd);
}
}

有时,在将数组写入文件时,fwrite可能会有点麻烦(哦,php的美丽)