您的网络服务(URL:http://api.minetools.eu/ping/play.desnia.net/25565)返回JSON。
这是一种标准格式,PHP(至少从 5.2 起)支持原生解码 - 你会从中得到某种形式的 PHP 结构。
您的代码当前不起作用(您的语法在 echo 上毫无意义 - 即使它是有效的,您也将原始 JSON 数据的字符串副本视为一个数组 - 这不起作用) ,您需要先让 PHP 解释(解码)JSON 数据:
http://php.net/manual/en/function.json-decode.php
<?php
$statisticsJson = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$statisticsObj = json_decode($statisticsJson);
如果发生错误,您的 $statisticsObj 将是 NULL - 您可以使用其他标准 PHP 函数获取该错误:
http://php.net/manual/en/function.json-last-error.php
假设它不是 NULL,您可以使用 var_dump($statisticsObj) 检查对象的结构 - 然后更改您的代码以适当地打印出来。
简而言之,类似于:
<?php
$statisticsJson = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$statisticsObj = json_decode($statisticsJson);
if ($statisticsObj !== null) {
echo $statisticsObj->players->online;
} else {
echo "Unknown";
}
您还应该检查从file_get_contents() 返回的内容 - 各种返回值可能会在错误时返回(这会炸毁json_decode())。有关可能性,请参阅文档:
http://php.net/manual/en/function.file-get-contents.php
我还将整个内容包装在一个函数或类方法中,以保持代码整洁。一个简单的“几乎完整”的解决方案可能如下所示:
<?php
function getServerStatistics($url) {
$statisticsJson = file_get_contents($url);
if ($statisticsJson === false) {
return false;
}
$statisticsObj = json_decode($statisticsJson);
if ($statisticsObj !== null) {
return false;
}
return $statisticsObj;
}
// ...
$stats = getServerStatistics($url);
if ($stats !== false) {
print $stats->players->online;
}
如果您想更好地处理服务器/HTTP 错误等,我会考虑使用 curl_*() - http://php.net/manual/en/book.curl.php
理想情况下,您还应该确认从您的网络服务返回的结构是您所期望的,然后再盲目地做出假设。您可以使用 property_exists() 之类的东西来做到这一点。
黑客愉快!