2013-11-24 16 views
0

我試圖提取特定值從谷歌API返回從JSON輸出的數組返回元件

<?php 
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false'; 

$contents = file_get_contents($url); 
$contents = utf8_encode($contents); 
$array=json_decode($contents); 
echo $array['rows']['elements']['distance']['value']; 

?> 

我預期要返回的4238值。相反,我得到一個錯誤:

`PHP Fatal error: Cannot use object of type stdClass as array in test9.php on` line 7 

回答

0

下面的代碼解決了這個問題:

$array=json_decode($contents, true); 
echo $array['rows'][0]['elements'][0]['distance']['value']; 
1

特正確的解決辦法是:

echo $array->rows[0]->elements[0]->distance->value; 

執行以下操作看JSON:

<?php 

$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false'; 

$contents = file_get_contents($url); 
$contents = utf8_encode($contents); 
echo "<pre>"; 
echo $contents; 
echo "\n"; 
echo "\n"; 
$array=json_decode($contents); 
echo $array->rows[0]->elements[0]->distance->value; 

?> 

http://www.json.org/

你有沒有試過node.js?