Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.
JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.
JSON is built on two structures:
- A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
- An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.
The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.
PHP JSON extension
PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.
Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.
Converting PHP variables to JSON using json_encode() function
To get a JSON representation of a variable, you use the json_encode()
function:
json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
Code language: PHP (php)
The following example uses the json_encode()
function to convert an indexed array in PHP to JSON format:
<?php
$names = ['Alice', 'Bob', 'John'];
$json_data = json_encode($names);
// return JSON to the browsers
header('Content-type:application/json');
echo $json_data;
Code language: PHP (php)
How it works.
- First, define an array of strings that consists of three elements.
- Second, convert the array to JSON using the
json_encode()
function. - Third, return the JSON data to the browsers by setting the content type of the document to
appplication/json
using theheader()
function.
Output:
[
"Alice",
"Bob",
"John"
]
Code language: JSON / JSON with Comments (json)
The following example uses the json_encode()
function to convert an associative array in PHP to an object in JSON:
<?php
$person = [
'name' => 'Alice',
'age' => 20
];
header('Content-type:application/json');
echo json_encode($person);
Code language: PHP (php)
Output:
{
name: "Alice",
age: 20
}
Code language: PHP (php)
In practice, you would select data from a database and use the json_encode()
function to convert it to the JSON data.
Converting JSON data to PHP variables
To convert JSON data to a variable in PHP, you use the json_decode()
function:
json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixed
Code language: PHP (php)
The following example shows how to use json_decode()
function to convert JSON data to a variable in PHP:
<?php
$json_data = '{"name":"Alice","age":20}';
$person = json_decode($json_data);
var_dump($person);
Code language: PHP (php)
Output:
object(stdClass)#1 (2) {
["name"] => string(5) "Alice"
["age"] => int(20)
}
Code language: PHP (php)
In this example, the json_decode()
function converts an object in JSON to an object in PHP. The object is an instance of the stdClass
class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.
Serializing PHP objects
To serialize an object to JSON data, you need to implement the JsonSerializable
interface. The JsonSerializable
interface has the jsonSerialize()
method that specifies the JSON representation of the object.
For example, the following shows how to implement the JsonSerializable
interface and use the json_encode()
function to serialize the object:
<?php
class Person implements JsonSerializable
{
private $name;
private $age;
public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}
public function jsonSerialize()
{
return [
'name' => $this->name,
'age' => $this->age
];
}
}
// serialize object to json
$alice = new Person('Alice', 20);
echo json_encode($alice);
Code language: PHP (php)
Output:
{"name":"Alice","age":20}
Code language: PHP (php)
How it works.
- First, define a Person class that implements the JsonSerializable interface.
- Second, return an array that consists of name and age properties from the
jsonSerialize()
method. Thejson_encode()
function will use the return value of this method to create JSON data. - Third, create a new
Person
object and serialize it to JSON data using thejson_encode()
function.
Summary
- JSON is a lightweight data-interchange format.
- Use the
json_encode()
function to convert PHP variables to JSON. - Use the
json_decode()
function to convert JSON data to PHP variables. - Implement the
JsonSerializable
interface to specify the JSON representation of an object.