使用PHP附加JSON文件时的奇怪行为

时间:2013-12-08 15:42:57

标签: php json post

所以我有一个包含以下格式的篮球运动员信息的JSON文件:

[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]

我希望用户能够将自己的自定义播放器添加到此文件中。为此,我尝试以下方法:

<?php 
        $json = file_get_contents('json/players.json');
        $info = json_decode($json, true);
        $info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
        file_put_contents('json/players.json', json_encode($info));
    ?>

这种“有点”的作品。但是当我检查JSON文件时,我发现有3个新条目而不是1:

{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}

假设$ name =“Jeff”$ team = 3和$ ppg = 23(通过POST提交填充)。

发生了什么,我该如何解决?

2 个答案:

答案 0 :(得分:0)

试试这个:

<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];

//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
        //Open the file
        $fh = fopen('json/players.json', 'r+') or die("can't open file");

        //get file info/stats
        $stat = fstat($fh);

        //final desired size after trimming the trailing ']'
        $size = $stat['size']-1;

        //file has contents? then remove the trailing ']'
        if($size>0) ftruncate($fh, $size);

        //close the current handle
        fclose($fh);

        // reopen the file for append
        $fh = fopen('json/players.json', 'a');

        //build your data array
        $info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
         //if this is not the first item on file
        if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
        else fwrite($fh, '['.json_encode($info).']'); //first item on file
        fclose($fh);
}
?>

也许您的php配置未设置为将post / get变量转换为全局变量。这发生在我身上几次,所以我宁愿创建我期望从post / get请求中得到的变量。还要注意页面编码,从个人经验来看,你可能会在那里得到空字符串。

答案 1 :(得分:0)

您可以尝试执行以下操作:

未经测试的代码

<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
    $fh = fopen('json/players.json', 'r+') or die("can't open file");
    $stat = fstat($fh);
    ftruncate($fh, $stat['size']-1);//removes last ] char
    fclose($fh); 
    $fh = fopen('json/players.json', 'a');
    $info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
    fwrite($fh, ','.json_encode($info).']');
    fclose($fh);
}
?>

这将只将新json附加到文件而不是打开文件,使php解析所有json,然后再将其写入文件。除此之外,如果变量实际包含数据,它将仅存储数据。