php

PHP – Read JSON file

In this tutorial, we are going to see how to read JSON file with PHP. JSON is used to transmit data between a server and a client. Here is a basic example of what could be in a JSON file.

{
   "name" : "Alex",
   "age" :  "25",
   "address" : "New York"
};

 

How to read JSON file with PHP

We can get the contents of a JSON file instead of keeping it as a PHP string. This is what the file.json file will look like.

[{
	"name" : "Alex",
	"age" :  "25",
	"address" : "New York"
}, {
	"name" : "Emily",
	"age" :  "18",
	"address" : "San Francisco"
}, {
	"name" : "Thomas",
	"age" :  "22",
	"address" : "Los Angeles"
}]

 

 
And here is how we will get the data from the above file in PHP.

// path to your JSON file
$file = 'file.json'; 
// put the content of the file in a variable
$data = file_get_contents($file); 
// JSON decode
$obj = json_decode($data); 
// display the name of the first person
echo $obj[0]->name;

Output:

Alex
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *