2016-05-06 113 views
-1

Null值EDITED写入JSON文件用PHP

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

期望 - 捕获数据输入HTML表格,追加它到一个现有的JSON文件。

一些我使用堆栈资源:

我的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脚本看起来像这样(更新实现斋的代码):

<?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> 
+2

你检查,如果所有这些$ _ POST包含有效的数值?回声他们看到他们的价值(如'var_dump($ _ POST)')。 –

+0

null在哪里?整个数组是null还是只有一个元素? – WillardSolutions

+0

所有元素为空:{“records”:{“Date”:null,“Miles”:null,“Gallons”:null,“Cost”:null,“MPG”:null,“Street”:null, “:null,”State“:null,”Zip“:null,”Time“:null}} –

回答

0

我敢肯定,你的提交没有POST的东西,因为你使用的锚(没有任何JavaScript)提交。换句话说,请注意我将它更改为<button>

<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很多:)

+0

@ Do not Panic建议提交按钮,它将数据发送到JSON文件,但是数据正在被覆盖而不被附加。 –

+0

从'fopen($ filename,'w +')将'w +'更改为'a'或'a +';'@GenericCog – Chay22

+0

尝试将w +更改为'a'和'a +',但是数据未写入JSON文件。 –

0

这个:

<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); 
+0

提交按钮确实将数据发送到JSON文件,非常感谢!但是,所有其他数据都会被覆盖,只剩下最新的输入。 –

+0

哦,你想要将你的表单数据追加到文件中现有的JSON中? –

+0

这是正确的。追加是我的目标。 –