Convert PHP Object To JSON | PHP Array To JSON
Since JSON is a ubiquitous data format for sharing and storing data, a PHP backend must allow JSON data processing. In this tutorial, we’ll learn about the JSON format and convert PHP Object to JSON.
Contents
Definitions
Array
Array is a data structure that contains a group of elements. In case you want to go deeper in arrays, click here to get it done using the official documentation.
Object
Object is an individual instance of the data structure defined by a class.
Example
Object 1 | Object 2 |
Name: Anisha Age: 24 | Name: Josie Age: 29 |
JSON
JSON (JavaScript Object Notation) is one of the most popular open-standard file formats used for storing and sharing data
json_encode()
It is an inbuild php function that is used to convert PHP array or object into JSON (JavaScript Object Notation) representation.
json_decode()
Takes a JSON (JavaScript Object Notation) encoded string and converts it into a PHP variable.
Convert PHP Array to JSON
First create an array.
$person = array('name' => 'Rhyley', 'email' => 'rhyley@company.com');
To convert it we use json_encode($person)
. Print the array and the json.
$person = array('name' => 'Rhyley', 'email' => 'rhyley@company.com');
print_r($person);
echo "---------------- \n";
echo json_encode($person);
Output
Array
(
[name] => Rhyley
[email] => rhyley@company.com
)
----------------
{"name":"Rhyley","email":"rhyley@company.com"}
Convert JSON To PHP Array
For JSON (JavaScript Object Notation) to PHP Array we use json_decode
.
$json = json_encode($person);
// print the array
print_r(json_decode($json));
Output
(
[name] => Rhyley
[email] => rhyley@company.com
)
Convert PHP Object to JSON
Let’s understand how we can JSON_encode a PHP object by creating an instance of Fruits.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function set_color($color){
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color(){
return $this->color;
}
}
$blackberries = new Fruit();
$blackberries->set_name('Blackberries');
$blackberries->set_color('Violet');
echo print_r($blackberries);
Output
Fruit Object
(
[name] => Blackberries
[color] => Violet
)
To convert a PHP Object to JSON we use json_encode
.
echo json_encode($blackberries);
Output
{"name":"Blackberries","color":"Violet"}
Conclusion
Now you can manipulate the data as well as you want. With this understanding of processing JSON (JavaScript Object Notation) data using PHP, go ahead and encode your PHP objects into JSON and share them across the internet.
We suggest you to continue learning more about arrays.
Thanks for reading!