2017-02-21 99 views
0

我想从json文件中获取数据,解析数据并将其添加到数据库中。我正在使用数据库,甲骨文。 我收到错误:从php中的JSON文件中获取数据

enter image description here

这是我的JSON文件

{ 
"data": { 
    "gps": [ 
     { "location": "45.778123,24.151165"  
     }, 
     { "location": "45.7875116,24.1549801"    
     } 
    ] 
} 

这是我的PHP文件

<?php 
     $file = 'JSONdata.json'; 
     $json = file_get_contents($file,0,null,null); 
     $obj = json_decode($json,true); 
     $data = $obj->data->gps; 

     include 'connection.php'; 

     function insert_data($connname, $conn) 
     { 
      foreach ($data as $post) { 
      $stmt = oci_parse($conn, "insert into GPSLOGS 
        values('".$post->location."')"); 
      oci_execute($stmt, OCI_DEFAULT); 
      echo "$connname inserted row without committing<br>\n"; 
      } 
     } 

     insert_data('c1', $conn); 
    ?> 

你知道我是什么做错了?为什么它不断得到这些错误? 我也尝试过使用另一种格式的JSON文件并以不同的方式进行解析,但它不断得到相同的错误。

.json 
     [{ "gps": "45.778123,24.151165"},{"gps": "45.7875116,24.1549801"}] 

.php 
    $file = 'JSONdata.json'; 
    $json = file_get_contents($file,0,null,null); 
    $obj = json_decode($json,true);  
     foreach($obj as $item) 
     {  echo $item['gps'];} 

回答

2
$obj = json_decode($json,true); 
$data = $obj->data->gps; 

在阵列的形式返回数据,不会反对。从json解码中删除第二个参数,一切都应该工作。

使其

$obj = json_decode($json); 
$data = $obj->data->gps; 
+0

谢谢。有效 –