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.


// 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:



2. Convert JSON String to PHP Object

Use json_decode function to convert a JSON string to object.


// JSON string
$jsonString = '{"name":"David","age":"20","gender":"male"}';

// convert JSON string to Object
$object = json_decode($jsonString);

// dump the object


object(stdClass)#1 (3) {
  string(5) "David"
  string(2) "20"
  string(4) "male"