2016-05-06 146 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

這是正確的。追加是我的目標。 –