JSON Encoding and Decoding in PHP
JSON stands for JavaScript Object Notation. It is an open, lightweight, text-based standard format developed for the exchange of human-readable data.
In this article, we will explore JSON encode and decode in PHP. PHP provides json_encode() and json_decode() functions to encode and decode JSON.
PHP JSON Encode
The json_encode() function returns the JSON of a value which means it convert PHP variable into JSON format. Now we are going to see the examples of code.
Example – 1
<?php $arr = array('Name' => 'Harry', 'Email' => '[email protected]', 'Phone' => '9876323456', 'Salary' => '30000'); echo json_encode($arr); ?>
Output
{"Name":"Harry","Email":"[email protected]","Phone":"9876323456","Salary":"30000"}
PHP JSON Decode
The json_decode() function decodes the JSON string, that is, converts the JSON string into a PHP variable.
Example – 1
<?php $arr = '{"Name":"Harry","Email":"[email protected]","Phone":"9876323456","Salary":"30000"}'; var_dump(json_decode($arr, true)); // true indicates to convert the returned object into an associative array ?>
Output
array(4) { ["Name"]=> string(5) "Harry" ["Email"]=> string(15) "[email protected]" ["Phone"]=> string(10) "9876323456" ["Salary"]=> string(5) "30000" }
Also, refer
Leave a Reply