PHP Object to JSON
From w3cyberlearnings
Contents |
PHP Object To JSON
In order to convert Object to JSON data, firstly you need to convert the object to an array. Finally, you need to use the json_encode() function to convert the array to JSON data. For complex Object, you need to use the custom function to do the conversion from object to an array recursively.
Example 1: Convert a simple object to an array
<?php $object = new stdClass(); $object->name = "Bob Markina"; $object->age = 24; $my_json = json_encode((array) $object); print_r($my_json); ?>
Output
{ name: "Bob Markina", age: 24 }
PHP Function to convert object to an array recursively
For complex object, you need to use this function to convert object to an array recursively.
<?php function objectToArray($d) { if (is_object($d)) { // Gets the properties of the object $d = get_object_vars($d); } if (is_array($d)) { return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } ?>
Example 2
This is a complex object, you require to use the custom function to convert the object to array recursively.
<?php require_one 'myfunction.php'; $employee_obj = new stdClass(); $employee_obj->name = 'Jamy Jo'; $employee_obj->age = 58; $employee_obj->address->street = '240 Lake Rd'; $employee_obj->address->apartment = '240'; $employee_obj->address->state = 'Tx'; $employee_obj->address->city = 'Houston'; $employee_obj->address->zip = '77300'; $employee_obj->role = 'PHP Developer'; // convert to json data $my_json = json_encode(objectToArray($employee_obj)); print_r($my_json); ?>
Output
{ name: "Jamy Jo", age: 58, address: { street: "240 Lake Rd", apartment: "240", state: "Tx", city: "Houston", zip: "77300" }, role: "PHP Developer" }
Related Links
--PHP Object to Array-- PHP Object to JSON-- PHP Access Object--