I have the URL http://api.minetools.eu/ping/play.desnia.net/25565 which outputs statistics of my server.
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.
Code to read API data using PHP file_get_contents() function PHP inbuilt file_get_contents() function is used to read a file into a string. This can read any file or API data using URLs and store data in a variable. This function is the easiest method to read any data by passing API URL.
An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.
1) Don't use file_get_contents()
(If you can help it)
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.
Generally a good alternative is curl()
2) Using curl()
to perform a GET
request
This is pretty straight forward. Issue a GET
request with some headers using 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
The response comes back in a JSON object. We can use json_decode()
to put this into a usable object or array.
$response = json_decode($response, true); //because of true, it's in an array
echo 'Online: '. $response['players']['online'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With