PHP: REST API – file_get_contents()

The easiest way to read data from an API in PHP is the built-in file_get_contents() function. It reads a file into a string, and it can read a URL also. Most APIs answer a GET request with JSON, so you read the text and decode it. New to APIs? Read the REST API introduction first.


Read API data

The API URL of this example returns the data of user 1 in JSON format.

https://jsonplaceholder.typicode.com/users/1
<?php
$url = "https://jsonplaceholder.typicode.com/users/1";

$response = file_get_contents($url);

if ($response === false) {
    die("Could not read the API.");
}

$user = json_decode($response, true);

echo $user["name"] . "<br>";
echo $user["email"];
?>

Output:

Tutorials Class - Output Window

Leanne Graham
Sincere@april.biz

  • file_get_contents() sends a GET request and returns the response body as a string, or false on failure.
  • json_decode($response, true) converts the JSON to a PHP array.
  • The setting allow_url_fopen must be On in php.ini. It is On by default, but some hosts turn it off.

Handle JSON errors

If the API sends wrong or empty JSON, json_decode() returns NULL. From PHP 7.3 you can ask it to throw an exception.

<?php
$response = '{"name": "Robin"';   // wrong JSON, bracket is missing

try {
    $data = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Invalid JSON: " . $e->getMessage();
}
?>

Output:

Tutorials Class - Output Window

Invalid JSON: Syntax error


Send a header or a POST request

You can pass a stream context as the third parameter to set the method, headers and a timeout. For more than simple requests, cURL is easier.

<?php
$options = [
    "http" => [
        "method"  => "GET",
        "header"  => "Accept: application/json\r\n",
        "timeout" => 10
    ]
];

$context = stream_context_create($options);
$response = file_get_contents("https://jsonplaceholder.typicode.com/users/1", false, $context);
?>

file_get_contents() or cURL?

file_get_contents()cURL
Very short codeA few more lines
Good for simple GETGood for GET, POST, PUT, DELETE
Hard to read the status code and errorsGives the status code and clear error messages
Needs allow_url_fopenNeeds the cURL extension (almost always installed)

Next chapter: GET data using cURL.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.