Parse JSON file with PHP

JSON (Java Script Object Notation) is fast becoming the most common data format for asynchronous browser-server communication. Standard functions are available in PHP for generating, parsing and interpreting JSON format. The PHP program in this how-to guides reads a JSON file into a JSON string and uses json_decode() function to convert the JSON string into a PHP variable.

JSON data consists of nested attribute-value pairs. Consider a JSON file students.json containing student names, age and address.



[
 {"name":"Adam","Age":18,
 	"Address":{"Street":"1000 Brooklyn Meadow","City":"Denver"}},
 {"name":"Bob","Age":30,
 	"Address":{"Street":"23 Sharp Crescent","City":"Bristol"}},
 {"name":"Kaneko","Age":27,
 	"Address":{"Street":"7 Yuki Street","City":"Tokyo"}}
]

The following PHP program parse this JSON file into a nested array

<?php

// Read JSON file
$json = file_get_contents('./student_data.json');

//Decode JSON
$json_data = json_decode($json,true);

//Print data
print_r($json_data);

?>

Output is as below:

Array
(
    [0] => Array
        (
            [name] => Adam
            [Age] => 18
            [Address] => Array
                (
                    [Street] => 1000 Brooklyn Meadow
                    [City] => Denver
                )

        )

    [1] => Array
        (
            [name] => Bob
            [Age] => 30
            [Address] => Array
                (
                    [Street] => 23 Sharp Crescent
                    [City] => Bristol
                )

        )

    [2] => Array
        (
            [name] => Kaneko
            [Age] => 27
            [Address] => Array
                (
                    [Street] => 7 Yuki Street
                    [City] => Tokyo
                )

        )

)

So json_decode converts the JSON data to a nested array. If you want to interpret the data or process it, you may need to traverse it, either using foreach loops or using iterators.

The following code sample prints out the students whose age is less than 20.


<?php

// Read JSON file
$json = file_get_contents('./student_data.json');

//Decode JSON
$json_data = json_decode($json,true);

//Traverse array and get the data for students aged less than 20
foreach ($json_data as $key1 => $value1) {
	if($json_data[$key1]["Age"] < 20){
		print_r($json_data[$key1]);
		}
}
?>

Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.