Convert PHP Object To / From JSON String
This post shows you how to convert an Object to / from JSON String in PHP.
1. Convert PHP Object To JSON String
Use json_encode
function to convert an object to JSON string.
example1.php
<?php
// create a new object
$object = new stdClass();
$object->name = 'David';
$object->age = '20';
$object->gender = 'male';
// convert the object to JSON string
$jsonString = json_encode($object);
JSON string:
{"name":"David","age":"20","gender":"male"}
2. Convert JSON String to PHP Object
Use json_decode
function to convert a JSON string to object.
example2.php
<?php
// JSON string
$jsonString = '{"name":"David","age":"20","gender":"male"}';
// convert JSON string to Object
$object = json_decode($jsonString);
// dump the object
var_dump($object);
Object:
object(stdClass)#1 (3) {
["name"]=>
string(5) "David"
["age"]=>
string(2) "20"
["gender"]=>
string(4) "male"
}