PHP-从url获取json数据


PHP - get json data from url

我正在尝试从这个url加载json数据=http://api.opencagedata.com/geocode/v1/json?query=48.84737%2C2.28605&漂亮=1&no_annotations=1&no_depe=1&密钥=b61388b5a248b7cfcaa9579ed290485b

使用file_get_contents可以与其他json url一起使用,但这一个很奇怪。它只返回第一行的"{"。Strlen给出了1480,这是正确的。Substr(2,18)给出了"documentation",这也是正确的。但我仍然无法回显整个文本。也许有办法逐行读取文本并将其保存在另一个字符串中?整个文本仍然完全加载在文本文件中这是我尝试的php代码

<?php
$url = file_get_contents("http://api.opencagedata.com/geocode/v1/json?query=48.84737%2C2.28605&pretty=1&no_annotations=1&no_dedupe=1&key=b61388b5a248b7cfcaa9579ed290485b");
$save = file_put_contents("filename.txt", $url);
echo $url;
?>

也尝试过这个功能,但还是一样。

function get_data($url) {
 $ch = curl_init();
 $timeout = 5;
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 $data = curl_exec($ch);
 curl_close($ch);
 return $data;
}

您可以使用json_decode获取返回值。

function get_data($url) {
 $ch = curl_init();
 $timeout = 5;
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 $data = curl_exec($ch);
 curl_close($ch);
 return json_decode($data,true);
}