2016-05-06 10 views
-1

Nullwert zu JSON-Datei geschrieben mit PHP

Problem EDITED - Ein Nullwert wird auf die JSON-Datei geschrieben, nachdem die Funktion ausgeführt wird.

Erwartung - Capture-Daten in HTML-Formular eingegeben, anhängen es zu einer vorhandenen JSON-Datei.

Einige der Stack-Ressourcen, die ich verwendet habe:

Meine JSON-Datei sieht wie folgt aus:

{ 
"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 
} 

EDITED - Mein PHP-Skript sieht wie folgt aus (Update implementiert Chay Code):

<?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); 
} 
?> 

Ein Auszug aus dem HTML-Formular aussieht dies:

<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

Haben Sie überprüft, ob alle, die $ _POST gültige Werte enthalten? Echo sie, um ihre Werte zu sehen (wie 'var_dump ($ _ POST)'). –

+0

Wo ist der Null? Ist das gesamte Array null oder nur ein Element? – WillardSolutions

+0

Alle Elemente sind null: {"records": {"Datum": null, "Meilen": null, "Gallonen": null, "Kosten": null, "MPG": null, "Straße": null, "Stadt ": null," Status ": null," Zip ": null," Zeit ": null}} –

Antwort

0

Ich bin sicher, dass Ihre Vorlage nicht POST etwas, da Sie Anker verwenden (ohne Javascript) einzureichen. In dem anderen Wort bemerke ich, dass ich es in <button> ändere.

<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> 

Wenn Sie auch bemerkt, ich änderte auch die zweiten input Namen oben auf mpg_num. Und das sollte dein Backend sein.

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

Aktualisiert
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);   
} 

ich diese Menge Ihrer Umgebung RAM verbrauchen nicht hoffen :)

+0

@ Do not Panic vorgeschlagen, die Schaltfläche Senden und es sendet die Daten an die JSON-Datei, aber die Daten werden überschrieben, nicht angehängt. –

+0

Ändern Sie 'w +' in 'a' oder' a + 'aus' fopen ($ filename, 'w +'); '@GenericCog – Chay22

+0

Versucht, w + auf 'a' und 'a +' zu ändern, aber die Daten wurden nicht in die geschrieben JSON-Datei. –

0

Dies ist:

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

wird tatsächlich Ihr Formular absenden. Wenn Sie nur so mit dem Skript verknüpfen, anstatt das Formular zu senden, wird keiner der $_POST Werte festgelegt.

Es sieht so aus, als ob Ihr Formular nur einen Absenden-Button benötigt. Sie können '_process.php?hello=true' in die Formularaktion einfügen, wenn Sie möchten, dass die if (isset($_GET['hello'])) { Prüfung funktioniert.

Mit anderen Worten:

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

Um die neuen Daten zu Ihrem bestehenden JSON zu anhängen, müssen Sie die Reihenfolge ändern, dass die Dinge in Ihrer Funktion geschehen. Der else Teil sollte wie folgt sein:

// 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

Der Submit-Button sendet die Daten an die JSON-Datei, danke dafür! Alle anderen Daten werden jedoch überschrieben, sodass nur die neuesten Daten gespeichert werden. –

+0

Oh, Sie möchten Ihre Formulardaten an den vorhandenen JSON in der Datei anhängen? –

+0

Das ist richtig. Append ist mein Ziel. –