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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么