1

我需要使用 php 将新的 geoJSON 功能写入 data.json 文件。现在我正在将我的数据写入文件,如下所示:

<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );

// Add the new data
$jsondata []= array(
      'measure_location'=> $_POST["measure_location"],
      'measure_type'=> $_POST["measure_type"],
      'measurement'=> $_POST["measurement"], 
      'note_text'=> $_POST["note_text"]
    );

// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);

// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>

这就是 data.json 中数据的样子:

 {
    "measure_location": "52.370611247493486, 4.91587221622467",
    "measure_type": "negative",
    "measurement": "violence",
    "note_text": ""
 }

我可以调整我的 PHP 代码以使数据看起来像这样:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [
      "4.91587221622467",
      "52.370611247493486"
    ]
  },
  "properties": {
    "type": "negative",
    "input": "violence",
    "note": ""
  }
}
4

1 回答 1

2

感谢 charlietfl 得到了答案。将php代码更改为:

<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );

// Add the new data
$jsondata [] = array(
                  'type' => 'Feature',
                  'geometry' => array(
                    'type' => 'Point',
                    'coordinates' => $_POST["measure_location"],
                  ),
                  'properties' => array(
                    'type' => $_POST["measure_type"],
                    'input' => $_POST["measurement"],
                    'note' => $_POST["note_text"],
                  )
                );

// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);

// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
于 2015-07-19T21:09:48.853 回答