0
0
PhpHow-ToBeginner · 3 min read

How to Read JSON File in PHP: Simple Guide

To read a JSON file in PHP, use file_get_contents to get the file content as a string, then convert it to a PHP array or object using json_decode. This lets you work with the JSON data easily in your PHP code.
📐

Syntax

Use file_get_contents to read the JSON file content as a string. Then use json_decode to convert the JSON string into a PHP variable (array or object).

  • file_get_contents('filename.json'): Reads the whole file content.
  • json_decode(string, true): Converts JSON string to PHP array if true is passed; otherwise, it returns an object.
php
<?php
$jsonString = file_get_contents('data.json');
$data = json_decode($jsonString, true); // true returns associative array
?>
💻

Example

This example reads a JSON file named data.json and prints the decoded PHP array.

php
<?php
// Read JSON file content
$jsonString = file_get_contents('data.json');

// Decode JSON to PHP associative array
$data = json_decode($jsonString, true);

// Print the array
print_r($data);
?>
Output
Array ( [name] => John [age] => 30 [city] => New York )
⚠️

Common Pitfalls

Common mistakes when reading JSON files in PHP include:

  • Not checking if the file exists or is readable before calling file_get_contents.
  • Not handling json_decode errors, which can happen if the JSON is invalid.
  • Forgetting to pass true to json_decode if you want an associative array instead of an object.

Always check for errors to avoid unexpected bugs.

php
<?php
// Wrong way: no error checks
$jsonString = file_get_contents('missing.json');
$data = json_decode($jsonString, true);

// Right way: with error checks
$filename = 'data.json';
if (file_exists($filename) && is_readable($filename)) {
    $jsonString = file_get_contents($filename);
    $data = json_decode($jsonString, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        print_r($data);
    } else {
        echo 'JSON decode error: ' . json_last_error_msg();
    }
} else {
    echo 'File not found or not readable';
}
?>
📊

Quick Reference

FunctionPurposeExample
file_get_contentsReads entire file content as stringfile_get_contents('file.json')
json_decodeConverts JSON string to PHP variablejson_decode($jsonString, true)
json_last_errorChecks last JSON error codejson_last_error()
json_last_error_msgReturns last JSON error messagejson_last_error_msg()

Key Takeaways

Use file_get_contents to read the JSON file content as a string.
Use json_decode to convert JSON string into a PHP array or object.
Always check if the file exists and is readable before reading.
Handle json_decode errors using json_last_error and json_last_error_msg.
Pass true to json_decode to get an associative array instead of an object.