douzhao7445 2015-07-19 20:21
浏览 165
已采纳

使用php将geoJSON写入.json文件

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": ""
  }
}
  • 写回答

1条回答 默认 最新

  • dongluo3962 2015-07-19 21:09
    关注

    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));
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机