【问题标题】:Null value written to JSON file with PHP使用 PHP 将空值写入 JSON 文件
【发布时间】:2016-09-02 01:04:02
【问题描述】:

已编辑

问题 - 函数运行后将空值写入 JSON 文件。

期望 - 捕获输入到 HTML 表单中的数据,追加到现有的 JSON 文件。

我使用过的一些 Stack 资源:

我的 JSON 文件如下所示:

{
"records": [
{"Date":"05/04/2016","Miles":168081,"Gallons":11.003,"Cost":28.60,"MPG":24.1,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"07:04"},
{"Date":"04/18/2016","Miles":167815,"Gallons":10.897,"Cost":27.23,"MPG":25.7,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"15:46"}
],
    "error" : false,
    "status" : 200
}

已编辑 - 我的 PHP 脚本如下所示(更新实现了 Chay 的代码):

<?php
  function runMyFunction() { 
    // #####
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
        die('I need post method!');
    }

    // check if file exists
    $filename = 'mpg-data-file2.json';
    if ( ! file_exists($filename) ) {
        echo 'ERROR:' . $filename . ' not found' . '<BR>';
    } else {
        echo 'OK: ' . $filename . ' exists.' . '<BR>';

        $data = array(
                "Date"=> $_POST['mpg_date'],
                "Miles"=> $_POST['mpg_miles'],
                "Gallons"=> $_POST['mpg_gallons'],
                "Cost"=> $_POST['mpg_cost'],
                "MPG"=> $_POST['mpg_mpg'],
                "Street"=> $_POST['mpg_street'],
                "City"=> $_POST["mpg_city"],
                "State"=> $_POST['mpg_state'],
                "Zip"=> $_POST['mpg_zip'],
                "Time"=> $_POST['mpg_time']
            );

        //Load data from json file
        $dataFile = file_get_contents("mpg-data-file2.json");
        $dataFile = json_decode($str_data,true);

        //Merge data from post with data from file
        $formattedData = array_merge($dataFile['records'],$data);
        $formattedData = json_encode($formattedData);

        //If data from file is empty, just use data from post
        if (empty($dataFile)) {
           $formattedData = json_encode($data);
        }
        //Set a parent key
        $records['records'] = $formattedData;

        //Overwites everything
        /* $handle = fopen($filename,'a+');           
        fwrite($handle,$records);
        fclose($handle); */
            file_put_contents($filename,$records, FILE_APPEND | LOCK_EX);
        print_r($formattedData);
        echo 'OK: ' . '<BR>' . $records . '<BR>'; 
    }   
    // ##### 
  }//end runMyFunction
/*
  if (isset($_GET['hello'])) {
    runMyFunction();
  } */
  if(isset($_POST['mpg_date'],$_POST['mpg_date'],$_POST['mpg_miles'],$_POST['mpg_gallons'],$_POST['mpg_cost'],$_POST['mpg_mpg'],$_POST['mpg_street'],$_POST["mpg_city"],$_POST['mpg_state'],$_POST['mpg_zip'],$_POST['mpg_time'])) {
     runMyFunction($_POST);
 }
?>

HTML 表单的摘录如下所示:

    <form action="_process.php" method="POST" role="form">
  <div class="form-group">
    <label for="mpg_date">Fuel Date:</label>
    <input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
  </div>
  <div class="form-group">
    <label for="mpg_miles">Odometer (Miles):</label>
    <input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_miles" placeholder="167815">
  </div>
  <!-- And so on... -->
  <div>
    <a href='_process.php?hello=true'>Run PHP Function</a>
    </div> 
</form>

【问题讨论】:

  • 您是否检查过所有这些 $_POST 是否包含有效值?回应他们以查看他们的价值观(如var_dump($_POST))。
  • 空值在哪里?整个数组是空的,还是只有一个元素?
  • 所有元素为空:{"records":{"Date":null,"Miles":null,"Gallons":null,"Cost":null,"MPG":null," Street":null,"City":null,"State":null,"Zip":null,"Time":null}}
  • 您没有提交任何数据。提交按钮在哪里?您所拥有的只是将 hello 作为 GET 变量链接到 process.php。

标签: php json


【解决方案1】:

这个:

<a href='_process.php?hello=true'>Run PHP Function</a>

实际上会提交您的表单。如果您只是以这种方式链接到脚本而不是提交表单,则不会设置任何 $_POST 值。

看起来您的表单只需要一个提交按钮。如果您希望 if (isset($_GET['hello'])) { 检查起作用,可以将 '_process.php?hello=true' 放入表单操作中。

换句话说:

<form action="_process.php?hello=true" method="POST" role="form">
    <!-- All your inputs, etc. ...-->
    <input type="submit" value="Run PHP Function">
</form>

为了将新数据附加到现有 JSON,您需要更改函数中发生的事情的顺序。 else 部分应该是这样的:

// First get the existing JSON from the file and decode it
$str_data = file_get_contents("mpg-data-file.json"); // Get the JSON string
$data = json_decode($str_data,true);// json_decode expects the JSON data, not a file name

// Then create a new data array from the $_POST data and add it to the 'records' key
$new_data = array(
    "Date"=> $_POST['mpg_date'],
    "Miles"=> $_POST['mpg_miles'],
    "Gallons"=> $_POST['mpg_gallons'],
    "Cost"=> $_POST['mpg_cost'],
    "MPG"=> $_POST['mpg_mpg'],
    "Street"=> $_POST['mpg_street'],
    "City"=> $_POST["mpg_city"],
    "State"=> $_POST['mpg_state'],
    "Zip"=> $_POST['mpg_zip'],
    "Time"=> $_POST['mpg_time']
);
$data['records'][] = $new_data;

// Then re-encode the JSON and write it to the file
$formattedData = json_encode($data);//format the data   
$handle = fopen($filename,'w+');//open or create the file           
fwrite($handle,$formattedData);//write the data into the file   
fclose($handle);//close the file
print_r($data);

【讨论】:

  • 提交按钮确实将数据发送到 JSON 文件,谢谢!但是,所有其他数据都会被覆盖,只留下最新输入的数据。
  • 哦,您想将表单数据附加到文件中现有的 JSON 中吗?
  • 实施时,脚本会为 JSON 值写入“null”。我可以发布一个实时网站的链接吗?
  • 好的,我去看看。
【解决方案2】:

我确定您的提交不是 POST 的东西,因为您使用的是锚(没有任何 javascript)提交。换句话说,请注意我将其更改为&lt;button&gt;

<form action="_process.php" method="POST" role="form">
  <div class="form-group">
    <label for="mpg_date">Fuel Date:</label>
    <input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
  </div>
  <div class="form-group">
    <label for="mpg_miles">Odometer (Miles):</label>
    <input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_num" placeholder="167815">
  </div>
  <!-- And so on... -->
  <div>
    <button type="submit" role="button">Run PHP Function</button>
  </div> 
</form>

如果您还注意到我还将上面的第二个 input 名称更改为 mpg_num。这应该是您的后端外观。

...
...
if(isset($_POST['mpg_date'], $_POST['mpg_num'])) {
    runMyFunction($_POST);
}

更新

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
    die('I need post method!');
}

// check if file exists
$filename = 'mpg-data-file.json';
if ( ! file_exists($filename) ) {
    echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
    echo 'OK: ' . $filename . ' exists.' . '<BR>';

    $data = array(
            "Date"=> $_POST['mpg_date'],
            "Miles"=> $_POST['mpg_miles'],
            "Gallons"=> $_POST['mpg_gallons'],
            "Cost"=> $_POST['mpg_cost'],
            "MPG"=> $_POST['mpg_mpg'],
            "Street"=> $_POST['mpg_street'],
            "City"=> $_POST["mpg_city"],
            "State"=> $_POST['mpg_state'],
            "Zip"=> $_POST['mpg_zip'],
            "Time"=> $_POST['mpg_time']
        );

    //Load data from json file
    $dataFile = file_get_contents("mpg-data-file.json");
    $dataFile = json_decode($str_data,true);

    //Merge data from post with data from file
    $formattedData = array_merge($dataFile['records'],$data);

    //If data from file is empty, just use data from post
    if (empty($dataFile)) {
       $formattedData = $data;
    }
    //Set a parent key
    $records['records'] = $formattedData;
    $records['error'] = false;
    $records['status'] = 200;
    $records = json_encode($records);

    //Overwites everything
    $handle = fopen($filename,'w+');           
    fwrite($handle,$records);
    fclose($handle);

    print_r($records);        
}   

我希望这不会大量消耗您的环境 RAM :)

【讨论】:

  • @Don't Panic 建议提交按钮并将数据发送到 JSON 文件,但数据被覆盖而不是附加。
  • w+ 更改为aa+fopen($filename,'w+'); @GenericCog
  • 尝试将 w+ 更改为 'a' 和 'a+' 但是数据没有写入 JSON 文件。
  • 将帖子传递给函数参数。
  • 将更多 JSON 编码的数据直接附加到 JSON 文件通常不会产生有效的 JSON。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2019-10-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
相关资源
最近更新 更多