用PHP解析好奇的JSON数据

时间:2018-09-30 14:38:45

标签: php json url

我现在尝试了所有操作,但无法获得此json的值:

[
{
place_id: "39915085",
licence: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
osm_type: "node",
osm_id: "2986714415",
boundingbox: [
"48.6900961",
"48.6901961",
"9.1934061",
"9.1935061"
],
lat: "48.6901461",
lon: "9.1934561",
display_name: "Flughafen Stuttgart, 43, Flughafenstraße, Leinfelden-Echterdingen, Landkreis Esslingen, Regierungsbezirk Stuttgart, Baden-Württemberg, 70629, Deutschland",
class: "place",
type: "house",
importance: 0.101
}
]

我只想要“ lat”值,但无法通过以下方式获取它:

$url = 'https://nominatim.openstreetmap.org/search?q=Stuttgart+Airport&format=json';

$contents = file_get_contents($url);
$clima=json_decode($contents);
echo "test: ".$clima->lat;

我不明白:(

3 个答案:

答案 0 :(得分:0)

您可以使用cURL请求来实现此目的:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://nominatim.openstreetmap.org/search?q=Stuttgart+Airport&format=json'
));

echo json_decode(curl_exec($curl))->lat;

从外观上看,file_get_contents($url)正在从参数中剥离"。因此,您帖子中的JSON响应无效,json_decode()返回null。

答案 1 :(得分:0)

从技术上讲,您发布的不是JSON。

在JSON中,密钥用双引号引起来。

{
     "jsonKey":"jsonValue",
}

无论如何,一旦您获得了正确的JSON,就得到了这样的数组:

[
    {
        ....
        "lat":"48.6901461",
        ....
    }
]

您必须这样做:

$contents = file_get_contents($url);
$clima = json_decode($contents);
$latitude = $clima[0]->lat;

答案 2 :(得分:0)

这对我有用: https://help.openstreetmap.org/questions/59788/calling-nominatim-with-file_get_contents

  

PHP的file_get_contents()既不发送HTTP UserAgent,也不发送Referer,   这违反了服务器的使用策略。您可以轻松添加   通过创建合适的流上下文(例如,   

     

///创建流$ opts = array('http'=> array('header'=>“ User-Agent:   StevesCleverAddressScript 3.7.6 \ r \ n“)); $ context =   stream_context_create($ opts);

     

//使用在$ file =上方设置的HTTP标头打开文件   file_get_contents('http://nominatim.openstreetmap.org/search/q=Rome',   false,$ context);有关更多信息,请参见PHP用户手册。