How to parse a JSON File in PHP ?
In this article, we are going to parse the JSON file by displaying JSON data using PHP. PHP is a server-side scripting language used to process the data. JSON stands for JavaScript object notation. JSON data is written as name/value pairs.
Syntax:
{
“Data”:[{
“key”:”value”,
“key”:value,
“key n “:”value”
},
. . .
. . .
{
“key”:”value”,
“key”:value,
“key n “:”value”
}]
}
Example: The JSON notation for student details is as follows.
{
“Student”:[{
“Name”:”Sravan”,
“Roll”:7058,
“subject”:”java”
},
{
“Name”:”Jyothika”,
“Roll”:7059,
“subject”:”SAP”
}]
}
Advantages:
- JSON does not use an end tag.
- JSON is a shorter format.
- JSON is quicker to read and write.
- JSON can use arrays.
Approach: Create a JSON file and save it as my_data.json. We have taken student data in the file. The contents are as follows.
{
“Student”:[{
“Name”:”Sravan”,
“Roll”:7058,
“subject”:”java”
},
{
“Name”:”Jyothika”,
“Roll”:7059,
“subject”:”SAP”
}]
}
Use file_get_contents() function to read JSON file into PHP. This function is used to read the file into PHP code.
Syntax:
file_get_contents(path, file_name)
- file_name is the name of the file and path is the location to be checked.
- Use json_decode() function to decode to JSON file into array to display it.
It is used to convert the JSON into an array.
Syntax:
json_decode($json_object, true)
- $json_object is the file object to be read.
PHP code: The following is the PHP code to parse JSON file.
PHP
<?php // Read the JSON file $json = file_get_contents ( 'my_data.json' ); // Decode the JSON file $json_data = json_decode( $json ,true); // Display data print_r( $json_data ); ?> |
Output:
Array ( [Student] => Array ( [0] => Array ( [Name] => Sravan [Roll] => 7058 [subject] => java ) [1] => Array ( [Name] => Jyothika [Roll] => 7059 [subject] => SAP ) ) )
Please Login to comment...