Reading JSON in PHP
Opposite to the previous recipe, this recipe will explain how JSON strings can be read in PHP and converted to objects or arrays. Decoding JSON strings is very easy in PHP with its JSON functions.
Getting ready
Create a new folder named Recipe2
in the Chapter4
directory.
How to do it...
Create a file named
index.php
inRecipe2
folder.Now try to convert a JSON string to object using
json_decode()
method. After that, print the resulting object on screen. Forjson_decode()
, you can use the output from previous recipe which is a valid JSON string.<?php $json = <<<JSON { "origin":"Delhi", "destination":"London", "passengers": [ { "name":"Mr. Perry Mason", "type":"Adult", "age":28 }, { "name":"Miss Irene Adler", "type":"Adult", "age":25 } ], "travelDate":"17-Dec-2010" } JSON; echo '<pre>'; $objJson = json_decode($json); print_r ($objJson); echo '</pre>'; ?>
Run the
index.php
file in the browser...