Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET info from external API/URL using PHP

Tags:

php

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.

like image 910
Jeremy Avatar asked Oct 23 '15 12:10

Jeremy


People also ask

How get data from API URL in PHP?

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.

Can I use PHP for API?

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 Answers

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'];
like image 197
ʰᵈˑ Avatar answered Oct 06 '22 10:10

ʰᵈˑ