1

我正在尝试编写 PHP 代码来与 Mapquest 的 Open API / Open Street Map 服务的 JSON 输出进行交互。我在下面列出了它。我一直在我的 Drupal 6 实现中使用此代码。此代码不返回任何输出。当我使用它时,json_last_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;
}

您可以通过URL查看原始 JSON 输出。在这个函数中,我期望得到1.257899我的输出。我有两个问题:

(1) 我可以调用什么来从数组中取出物品。例如,如何"distance":26.923从数组中获取 JSON 中表示的值?

(2) 我是否有可能遇到我在PHP 手册中读到的递归限制问题?

4

2 回答 2

2

如果您仔细阅读 json_decode 的手册页,您会注意到有一个参数(默认为 false),您可以传递该参数以使其返回数组而不是对象。

$obj = json_decode($json, true);

所以:

<?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();
于 2012-12-05T02:15:32.870 回答
1

从 中删除该var_export功能json_decode

您正在尝试将有关字符串的信息转换为 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;
}
于 2012-12-05T02:02:53.747 回答