使用 PHP 从外部 API/URL 获取信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33302442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GET info from external API/URL using PHP
提问by Jeremy
I have the URL http://api.minetools.eu/ping/play.desnia.net/25565which outputs statistics of my server.
我有 URL http://api.minetools.eu/ping/play.desnia.net/25565它输出我的服务器的统计信息。
For example:
例如:
{
"description": "A Minecraft Server",
"favicon": null,
"latency": 64.646,
"players": {
"max": 20,
"online": 0,
"sample": []
},
"version": {
"name": "Spigot 1.8.8",
"protocol": 47
}
}
I want to get the value of online player count to display it on my website as: Online Players: online amount
我想获得在线玩家数量的值以在我的网站上显示为:在线玩家:在线数量
Can anyone help?
任何人都可以帮忙吗?
I tried to do:
我试图做:
<b> Online players:
<?php
$content = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
echo ($content, ["online"]);
}
?>
</b>
But it didn't work.
但它没有用。
回答by ???
1) Don't use file_get_contents()
(If you can help it)
1)不要使用file_get_contents()
(如果可以的话)
This is because you'd need to enable fopen_wrappers
to enable file_get_contents()
to work on an external source. Sometimes this is closed (depending on your host; like shared hosting), so your application will break.
这是因为你需要能够fopen_wrappers
使file_get_contents()
工作的外部源。有时这是关闭的(取决于您的主机;例如共享主机),因此您的应用程序将中断。
Generally a good alternative is curl()
通常一个好的选择是 curl()
2) Using curl()
to perform a GET
request
2)curl()
用于执行GET
请求
This is pretty straight forward. Issue a GET
request with some headers using curl()
.
这是非常直接的。发出GET
使用一些头要求curl()
。
$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) Using the response
3) 使用响应
The response comes back in a JSON object. We can use json_decode()
to put this into a usable object or array.
响应以JSON 对象返回。我们可以用json_decode()
它把它放到一个可用的对象或数组中。
$response = json_decode($response, true); //because of true, it's in an array
echo 'Online: '. $response['players']['online'];
回答by Aman Sura
Your server is returning a JSON string. So you should use json_decode()function to convert that into a plain PHP object. Thereafter you can access any variable of that object.
您的服务器正在返回一个 JSON 字符串。因此,您应该使用json_decode()函数将其转换为普通的 PHP 对象。此后,您可以访问该对象的任何变量。
So, something like this shall help
所以,这样的事情会有所帮助
<?php
$content = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$result = json_decode($content);
print_r( $result->players->online );
?>
More details for json_decode can be read here - http://php.net/manual/en/function.json-decode.php
可以在此处阅读 json_decode 的更多详细信息 - http://php.net/manual/en/function.json-decode.php
回答by wally
Your webservice (URL: http://api.minetools.eu/ping/play.desnia.net/25565) returns JSON.
您的网络服务(网址:http: //api.minetools.eu/ping/play.desnia.net/25565)返回JSON。
This is a standard format, and PHP (at least since 5.2) supports decoding it natively - you'll get some form of PHP structure back from it.
这是一种标准格式,并且 PHP(至少从 5.2 开始)支持对它进行本机解码 - 您将从中获得某种形式的 PHP 结构。
Your code currently doesn't work (your syntax is meaningless on the echo
- and even if it was valid, you're treating a string copy of the raw JSON data as an array - which won't work), you need to have PHP interpret(decode) the JSON data first:
您的代码当前不起作用(您的语法对echo
- 即使它有效,您也将原始 JSON 数据的字符串副本视为数组 - 这不起作用),您需要有 PHP首先解释(解码)JSON 数据:
http://php.net/manual/en/function.json-decode.php
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);
Your $statisticsObj
will be NULL
if an error occurred - and you can get that error using other standard PHP functions:
你$statisticsObj
会NULL
在发生错误的-你可以使用其他标准的PHP函数得到这个错误:
http://php.net/manual/en/function.json-last-error.php
http://php.net/manual/en/function.json-last-error.php
Assuming it isn't NULL
, you can examine the structure of the object with var_dump($statisticsObj)
- and then alter your code to print it out appropriately.
假设它不是NULL
,您可以使用var_dump($statisticsObj)
-检查对象的结构,然后更改您的代码以适当地打印出来。
In short, something like:
简而言之,类似于:
<?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";
}
You should also check what comes back from file_get_contents()
too - various return values can come back (which would blow up json_decode()
) on errors. See the documentation for possibilities:
您还应该检查返回的内容file_get_contents()
- 各种返回值可能会json_decode()
在错误时返回(这会爆炸)。有关可能性,请参阅文档:
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.file-get-contents.php
I'd also wrap the entire thing in a function or class method to keep your code tidy. A simple "almost complete" solution could look like this:
我还会将整个内容包装在一个函数或类方法中,以保持您的代码整洁。一个简单的“几乎完整”的解决方案可能如下所示:
<?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;
}
If you want better handling over server / HTTP errors etc, I'd look at using curl_*()
- http://php.net/manual/en/book.curl.php
如果你想更好地处理服务器/HTTP 错误等,我会考虑使用curl_*()
- http://php.net/manual/en/book.curl.php
Ideally you also should be confirming the structure returned from your webservice is what you expected before blindly making assumptions too. You can do that with something like property_exists()
.
理想情况下,您还应该在盲目做出假设之前确认从您的网络服务返回的结构是您所期望的。你可以用类似的东西来做到这一点property_exists()
。
Happy hacking!
快乐黑客!
回答by DrRobotNet
Since it's returning an array you should use print_r or var_dump instead of echo. Or perhaps it threw you an error.
由于它返回一个数组,因此您应该使用 print_r 或 var_dump 而不是 echo。或者它可能给你一个错误。