1)不要使用
file_get_contents()(如果可以帮助的话)
这是因为您需要enable fopen_wrappers才能使file_get_contents()能够处理外部源.有时这是关闭的(取决于您的主机;如共享主机),因此您的应用程序将会中断.
一般来说,一个很好的选择是curl()
2)使用curl()执行GET请求
这很简单.使用curl()发出带有一些标头的GET请求.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://api.minetools.eu/ping/play.desnia.net/25565",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
3)使用响应
响应在JSON object中返回.我们可以使用json_decode()将其放入可用的对象或数组中.
$response = json_decode($response, true); //because of true, it's in an array
echo 'Online: '. $response['players']['online'];