【问题标题】:HTTP Request in PHP not working for specific APIPHP 中的 HTTP 请求不适用于特定 API
【发布时间】:2015-02-16 02:02:57
【问题描述】:

我有一个非常简单的脚本:

<?php
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
echo $json;
?>

它适用于这个 URL,但是当我用这个 URL 调用它时:https://erikberg.com/nba/standings.json

它没有回显数据。这是什么原因?我可能在这里遗漏了一个概念。谢谢

【问题讨论】:

  • 您在服务器上为此正确配置了 ssl 吗?

标签: php json http request


【解决方案1】:

该特定 URL 的问题在于它需要一个不同的用户代理,与 PHP 与 file_get_contents() 一起使用的默认值不同

这是一个使用 CURL 的更好示例。它更加健壮,尽管它需要更多的代码行来配置它并使其运行:

// create curl resource
$ch = curl_init();

// set the URL
curl_setopt($ch, CURLOPT_URL, 'https://erikberg.com/nba/standings.json');

// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Fake the User Agent for this particular API endpoint
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

// $output contains the output string.
$output = curl_exec($ch);

// close curl resource to free up system resources.
curl_close($ch);

// You have your JSON response here
echo $output;

【讨论】:

  • 知道为什么运行如此缓慢吗?
  • 从我这边来看,它一点也不慢。该请求大约需要 1.25 秒。看起来很正常的响应时间。
  • 啊,哥奇亚,那一定是我的事了,这对我来说需要 15 秒以上。再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 2019-07-03
  • 2020-10-28
  • 2022-08-17
  • 2021-10-04
相关资源
最近更新 更多