Php 从URL解码JSON

Php 从URL解码JSON,php,json,Php,Json,我使用的API返回一个JSON字符串: 我感兴趣的部分是城市/城镇名称(在本例中为Hook Norton),我希望将其作为PHP变量。我知道JSON\u decode()函数在某些地方起作用,但如何访问API的输出?最简单的方法是使用file\u get\u contents,它可以处理web文档和本地文件。例如: $json = file_get_contents("http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&

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


我感兴趣的部分是城市/城镇名称(在本例中为Hook Norton),我希望将其作为PHP变量。我知道
JSON\u decode()
函数在某些地方起作用,但如何访问API的输出?

最简单的方法是使用
file\u get\u 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;

由于JSON是HTTP响应的一部分,因此需要使用PHP发出HTTP请求,并以字符串形式获取响应

这方面的瑞士刀是,但是(取决于您的需求和服务器的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
试试这个

$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;
$json=file\u get\u contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo');
$data=json_decode($json,true);

$Geonames=$data['Geonames'][0]; 回声“; 打印(地理名称); 出口
与其他数组或对象一样。非常感谢。如何仅为数组的一个元素(例如城镇名称)设置变量?$Geonames=$data['Geonames'][0]['keyname'];