phpjsongeojsonfile-put-contents

Write geoJSON to .json file using php


I need to write a new geoJSON feature to a data.json file using php. Right now I'm writing my data to the file like so:

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

And this is what the data then looks like in data.json:

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

Could I adjust my PHP code to make the data look like so:

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

Solution

  • Got the answer thanks to charlietfl. Changed the php code to:

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