使用PHP

时间:2016-05-06 20:45:55

标签: php json

EDITED

问题 - 函数运行后,空值将写入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>

2 个答案:

答案 0 :(得分:0)

此:

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

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

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

换句话说:

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

答案 1 :(得分: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很多:)