JSON to PHP Array using file_get_contents

JSON to PHP Array using file_get_contents

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

JSON to PHP Array using file_get_contents

When attempting to fetch data from a third-party API and convert it into a usable PHP structure, the most straightforward approach is often file_get_contents() paired with json_decode(). However, if your script returns an empty array, the issue almost never lies in the conversion logic itself. In the scenario described, where $data ends up as [], the root cause is typically a failure to retrieve the response body from the remote server before attempting to parse it.

The provided code snippet:

<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

relies on file_get_contents() to populate the $json variable. If this function fails—whether due to a network timeout, an invalid SSL certificate, or simply because the remote server returns an HTTP error code like 404 or 500—the $json variable will contain false. When you pass false into json_decode(), the function also returns null. While null isn't an empty array, if there is additional logic checking for a specific format that isn't shown here, it might appear as such. More critically, if the remote URL is unreachable or blocked by local network restrictions, file_get_contents() returns false without raising an error in older PHP versions unless error reporting is strict.

To debug this effectively, you must verify two things: whether the HTTP request succeeded and whether the raw response string matches the expected JSON structure. First, check the return value of file_get_contents():

$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);

if ($json === false) {
    // The request failed completely
    echo "Failed to fetch data. Check network or SSL.";
} else {
    // Proceed with decoding
    $data = json_decode($json, TRUE);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "JSON Decode Error: " . json_last_error_msg();
    } else {
        print_r($data);
    }
}

The structure of the incoming JSON is nested. The top-level object contains a bpath and a clist array. Each item in clist holds metadata like cid and ctitle, along with an alist containing individual news items. When decoded into a PHP associative array (the second argument to json_decode set to TRUE), this hierarchy is preserved exactly as shown in the source material:

$data[0]['bpath'] // Returns "http://www.sampledomain.com/"
$data[0]['clist'][0]['cid'] // Returns "11"
$data[0]['clist'][0]['alist'][0]['weburl'] // Returns "news.php?nid=6865"

A common pitfall when working with file_get_contents() is the handling of SSL certificates. If the API endpoint uses HTTPS and your server's CA bundle is outdated or missing, file_get_contents() will fail silently or throw a warning depending on your PHP configuration. In production environments, you should explicitly allow insecure connections for testing purposes only, or ensure your system has valid root certificates installed:

$context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);

$json = file_get_contents($json_url, false, $context);

Note that disabling peer verification is a security risk and should be avoided in live applications unless you have strict control over the certificate chain. A more robust solution involves using cURL, which provides better visibility into HTTP status codes and headers. With cURL, you can explicitly check if the response code is 200 OK before attempting to decode the JSON body:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only for testing with self-signed certs
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
    $data = json_decode($response, TRUE);
} else {
    echo "API returned HTTP code: $httpCode";
}

If you are working within the Laravel ecosystem, the HTTP client facade offers a cleaner abstraction for these operations. It handles error handling and SSL verification out of the box, reducing boilerplate code while maintaining type safety. For example, you could fetch this data directly in a controller or service class without worrying about stream contexts:

use Illuminate\Support\Facades\Http;

$response = Http::get($json_url);
if ($response->successful()) {
    $data = json_decode($response->body(), true);
}

The choice between file_get_contents and cURL often comes down to the complexity of the request. For simple GET requests where you don't need custom headers or timeouts, file_get_contents is perfectly adequate. However, if the API requires authentication tokens, specific user agents, or complex timeout logic, switching to cURL or Laravel's HTTP client becomes necessary. The key takeaway remains the same: always validate that you received a valid response string before attempting JSON parsing.

Our network