JSON with PHP Example: JSON Tutorial


JSON extension is a part of PHP 5.2.0.

JSON functions that are available in PHP.

  1. json_decode() : Decodes a JSON string
  2. json_encode() : Returns the JSON representation of a value
  3. json_last_error_msg() : Returns the error string of the last json_encode() or json_decode() call
  4. json_last_error() : Returns the last error occurred
PHP JSON encode function Examples :

PHP array to JSON Object :
<?php
  
//PHP array
$phpArray = array (
    'songName' => 'Hotel California',
    'artistName' =>'Eagles'
    );
  
  
//PHP array converted to json Object using json_encode()
echo json_encode($phpArray);

?>

Output: {"songName":"Hotel California","artistName":"Eagles"}

PHP Object to JSON Object :
<?php
  
//PHP Class
class Song {
	
 public $songName ="";
 public $songArtist ="";
 
}
 //PHP object
 $mySong = new Song();
 
 $mySong ->songName = "November rain";
 $mySong -> songArtist = "Guns and Roses";
  
 //JSON object
 $jsonObj = json_encode($mySong);
 
 echo $jsonObj;
?>

Output: {"songName":"November rain","songArtist":"Guns and Roses"}

PHP JSON encode function Examples :

JSON Object to PHP Array :
<?php
//JSON Object  
$jsonMySong = '{"songName":"November rain",
                 "songArtist":"Guns and Roses"}';
 
//PHP Array  
$phpArrayObj = json_decode($jsonMySong,true);
 
 var_dump($phpArrayObj);
?>

Output: array(2) {
["songName"]=> string(13) "November rain"
["songArtist"]=> string(14) "Guns and Roses"
}

JSON Object to PHP Object :
<?php
//JSON Object  
$jsonMySong = '{"songName":"November rain",
                 "songArtist":"Guns and Roses"}';
 
//PHP Object  
$phpyObj = json_decode($jsonMySong);
 
 var_dump($phpObj);
?>

Output: object(stdClass)#1 (2) {
["songName"]=> string(13) "November rain"
["songArtist"]=> string(14) "Guns and Roses"
}






Hello there!,

You are using AdBlocker!

I am an independent developer trying to help fellow developers and students to resolve issues faced on a day-to-day basis, we 'Code to Care' . There is a lot of expenses involved in hosting and managing a website that's the reason we have ads.

A humble request to you to disable adBlocker on Code2care.org and support us pay our bills.

Thanks,
Cod2care - Line's of code for change.

To see contents reload page after unblocking
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities. Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, Tips-n-tricks, How Tos, Blogs, Articles, etc. on various platforms like Windows, Mac, Linux, Mobile platforms, etc. Technologies/Languages like Java, Objective-C, PHP, .Net, Android, SharePoint, jQuery, HTML, CSS, etc.