【问题标题】:file_get_contents() returning raw data from url instead of json [duplicate]file_get_contents() 从 url 而不是 json 返回原始数据 [重复]
【发布时间】:2019-04-15 06:44:10
【问题描述】:

这个问题之前已经被问过很多次,但似乎没有一个解决方案有效。我想使用 file_get_contents()this url 返回 JSON 数据,但它以原始格式 (string) 返回 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 数据 (string)

$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);

我想要的输出

它给出的输出

【问题讨论】:

  • 我猜,作为重复链接的问题不是他所要求的。您宁愿寻找 application/json 标头。请参阅:stackoverflow.com/questions/4064444/… - 另外,您应该删除您的 API 密钥。
  • dd() 是 Laravel 的调试输出功能吧?那么是的,它只会按原样显示文字字符串。通常你会解码 JSON,然后用它做点什么。如果此脚本只是关于播放,那么 echo 和正确的 MIME 类型将使您的浏览器 JSON 美化器参与其中(如果这是您想要的,那么它可能值得一提)。
  • 解决后我会禁用这个键
  • 当我执行 json_decode() 时,它给了我错误 Call to undefined function GuzzleHttp\json_decode()

标签: php laravel-5.6


【解决方案1】:

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

【讨论】:

  • 当我执行 json_decode() 时,它给了我错误 Call to undefined function GuzzleHttp\json_decode()
  • 看起来您的 php 配置中没有启用 json 扩展。你应该安装 ext-json 并启用它。
猜你喜欢
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 2019-03-10
  • 1970-01-01
  • 2014-04-24
相关资源
最近更新 更多