在php中使用JSON_decode()映射数据的JSON输出
我试图编写PHP代码,与Mapquest的开放API/开放街道地图服务的JSON输出交互。我在下面列出了它。我一直在Drupal6实现中使用这段代码。此代码不返回任何输出。当我使用它时,在php中使用JSON_decode()映射数据的JSON输出,php,drupal-6,json,openstreetmap,mapquest,Php,Drupal 6,Json,Openstreetmap,Mapquest,我试图编写PHP代码,与Mapquest的开放API/开放街道地图服务的JSON输出交互。我在下面列出了它。我一直在Drupal6实现中使用这段代码。此代码不返回任何输出。当我使用它时,json\u last\u error()输出0 function json_test_page() { $url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&a
json\u last\u error()
输出0
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
您可以通过查看原始JSON输出。在这个函数中,我希望得到1.257899
作为我的输出。我有两个问题:
(1) 我可以调用什么以便从数组中获取项目。例如,如何从数组中获取JSON“distance”:26.923
中表示的值
(2) 我是否可能遇到了我在中读到的递归限制问题?从
json\u decode
中删除var\u export
函数
您正在尝试将有关字符串的信息转换为json
我可以通过这种方式获得fuelUsed
属性
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}
如果仔细阅读json_decode的手册页面,您会注意到有一个参数(默认情况下为false),您可以传递该参数以使其返回数组而不是对象
$obj = json_decode($json, true);
因此:
我同意这个答案,但根据最初的问题,我提供了一个替代方案,可以获得一个数组。这很好。工作如期进行。我知道TRUE
参数,但不知道使用json\u decode()
或其他方法解析数组是否最好。这似乎很管用。谢谢
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();