php 来自 URL 的 JSON 解码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6571090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:44:57  来源:igfitidea点击:

JSON decoding from a URL

phpjson

提问by Sebastian

I'm using an API which returns a JSON string:

我正在使用一个返回 JSON 字符串的 API:

http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo

http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo

The part I'm interested in is the city/town name (in this instance Hook Norton) which I'd like as a PHP variable. I understand the JSON_decode()function comes into play somewhere, but how do I access the output of the API?

我感兴趣的部分是我希望作为 PHP 变量的城市/城镇名称(在本例中为 Hook Norton)。我知道该JSON_decode()函数在某处发挥作用,但如何访问 API 的输出?

回答by Shashank Patel

Try this.

尝试这个。

$json = file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');

$data = json_decode($json,true);

$Geonames = $data['geonames'][0];

echo "<pre>";

print_r($Geonames);

exit;

回答by Ross

The simplest way is to use file_get_contents, which works on web documents as well as local files. For example:

最简单的方法是使用file_get_contents,它适用于 Web 文档和本地文件。例如:

$json = file_get_contents("http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo");
$data = json_decode($json);
echo $data->geonames[0]->toponymName;

回答by Jon

Since the JSON is part of the HTTP response, you need to make an HTTP request with PHP and get the response as a string.

由于 JSON 是 HTTP 响应的一部分,因此您需要使用 PHP 发出 HTTP 请求并将响应作为字符串获取。

The swiss knife for this is cURL, but (depending on your requirements and the server's PHP configuration) you are likely able to do this very simply like this:

瑞士刀是cURL,但是(取决于您的要求和服务器的 PHP 配置)您可能可以非常简单地执行此操作,如下所示:

$json = file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');
$data = json_decode($json);
// and now access the data you need