Creating JSON in PHP
This recipe will explain how JSON can be created from PHP arrays and objects.
Getting ready
Create a new folder inside the Chapter4
directory and name it as Recipe1
.
How to do it...
Create a file and save it by the name
index.php
in theRecipe1
folder.Write the PHP code that creates a JSON string from an array.
<?php $travelDetails = array( 'origin' => 'Delhi', 'destination' => 'London', 'passengers' => array ( array('name' => 'Mr. Perry Mason', 'type' => 'Adult', 'age'=> 28), array('name' => 'Miss Irene Adler', 'type' => 'Adult', 'age'=> 28) ), 'travelDate' => '17-Dec-2010' ); echo json_encode($travelDetails); ?>
Run the file in your browser. It will show a JSON string as output on screen. After indenting the result will look like the following:
{ "origin":"Delhi", "destination":"London", "passengers": [ { "name":"Mr. Perry Mason", "type":"Adult", "age":28 }, { "name...