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 iftrueis 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_decodeerrors, which can happen if the JSON is invalid. - Forgetting to pass
truetojson_decodeif 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
| Function | Purpose | Example |
|---|---|---|
| file_get_contents | Reads entire file content as string | file_get_contents('file.json') |
| json_decode | Converts JSON string to PHP variable | json_decode($jsonString, true) |
| json_last_error | Checks last JSON error code | json_last_error() |
| json_last_error_msg | Returns last JSON error message | json_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.