PHP中的HTTP请求不适用于特定的API


HTTP Request in PHP not working for specific API

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

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

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

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

该特定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;