首页 > 解决方案 > file_get_contents() 从 url 而不是 json 返回原始数据

问题描述

这个问题之前已经被问过很多次,但似乎没有一个解决方案有效。我想从这个 url返回 JSON数据file_get_contents(),但它以原始格式(字符串)返回 JSON 数据。

这是我的代码:

$data = file_get_contents('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins=27.696694861033567,83.46625594498187&destinations=28.233514383842977,83.98651076641227&travelMode=driving&key=bingmaps_api_key&distanceUnit=km');
dd($data);

我尝试使用 curl 但结果相同,它还以原始格式(字符串)返回 JSON 数据

$url = 'https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins=27.696694861033567,83.46625594498187&destinations=28.233514383842977,83.98651076641227&travelMode=driving&key=ingmaps_api_key&distanceUnit=km';
if (!function_exists('curl_init')) {
    die('The cURL library is not installed.');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
dd($output);

我想要的输出 产出

它给出的输出 所需输出

标签: phplaravel-5.6

解决方案


JSON 只不过是一个字符串。file_get_contents 或 cURL 将始终返回字符串,您必须使用json_decode方法解码字符串,该方法应该为您提供 JSON 对象。


推荐阅读