Skip to content

All topics  /  PHP

How to Read a JSON File in PHP?

PHP ·

Hi Dev,

In this post, we will learn How to Read Json File in php. I explained simply step by step php Open Read Json File. let’s discuss about How to Read a Json File in php. This tutorial will give you simple example of php Open and read Json File. you will do the following things for How to Read a Json File in php.

Here, I will give the following example of read a JSON file in the php program, we will use The file_get_contents() this function reads a file into a string and The json_decode() function is use to JSON encoded string and convert into a PHP variable.

Example: how to read json file in php


I simply created data.json file with content as like below:

data.json

[
    {
        "id": 1,
        "name": "Hardik Savani",
        "email": "[email protected]"
    },
    {
        "id": 2,
        "name": "Jaydeep Pathar",
        "email": "[email protected]"
    },
    {
        "id": 3,
        "name": "Vivek Pathar",
        "email": "[email protected]"
    }
]

index.php

<?php
   // Read the JSON file 
   $json = file_get_contents('data.json');
   // Decode the JSON file
   $json_data = json_decode($json,true);
   // Display data
   print_r($json_data);
?>

Output:

Array 
   ( 
      [0] => Array 
         ( [id] => 1 [name] => Hardik Savani [email] => [email protected] ) 
      [1] => Array 
         ( [id] => 2 [name] => Jaydeep Pathar [email] => [email protected] ) 
      [2] => Array 
         ( [id] => 3 [name] => Vivek Pathar [email] => [email protected] ) 
   )

I hope it could help you...