Thursday, April 18, 2013

How to parse JSON with PHP

Today's quick tip is an example how to parse JSON and output it as an array. We'll use file_get_contents to get the key value pairs from the JSON object and output the contents in a foreach loop.

Here's the php code :


<?php

$string = file_get_contents("file.json");

$string2 = json_decode($string,true);

foreach ($string2['Friends'] as $value) {

echo "First Name: " . $value['firstName'] . "<br />";
echo "Last Name: " . $value['lastName'] . "<br /><br />";

}

?>

Here is the JSON object:


{
"Friends":[

{"firstName":"John","lastName":"Doe"},
{"firstName":"Steve","lastName":"Jones"},
{"firstName":"Tom","lastName":"Smith"}
]
}


Check out my new gator hunting app for iPhone

1 comment: