【问题标题】:file_get_contents is not not capturing required datafile_get_contents 未捕获所需数据
【发布时间】:2020-01-18 22:20:17
【问题描述】:
$data = file_get_contents($url);

$result = json_decode($data, true); 

使用上面的代码,我想将下面的 url 输出捕获到 $data,但是 file_get_contents 没有给 $data 任何东西。请帮助我解决这个问题,也请让我知道 PHP 中是否有其他方法可以做到这一点。

{
   "destination_addresses" : [ "Boyces Rd, Wisbech PE13 2JT, UK" ],
   "origin_addresses" : [ "Battersea, London SW8 3QR, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "174 km",
                  "value" : 173989
               },
               "duration" : {
                  "text" : "2 hours 42 mins",
                  "value" : 9702
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

【问题讨论】:

  • 如果file_get_contents() 失败,那么您将收到警告。启用错误报告并检查您的网络服务器日志。
  • 检查 allow_url_open 是否设置为 on 或者您可以尝试使用 cURL 获取该内容。这里有一个例子:stackoverflow.com/questions/10354805/…

标签: php file-get-contents


【解决方案1】:

你可以通过多种方式做到这一点

例如:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));

使用上述方法,请确保您的服务器配置允许“allow_url_fopen”。

使用 curl 可以是另一种解决方案:

$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多