Chapter 13. JSON
Similar to XML, JavaScript Object Notation (JSON) was designed as a standardized data-interchange format. However, unlike XML, JSON is extremely lightweight and human-readable. While it takes many syntax cues from JavaScript, JSON is designed to be language-independent.
JSON is built on two structures: collections of name/value pairs called objects (equivalent to PHP’s associative arrays) and ordered lists of values called arrays (equivalent to PHP’s indexed arrays). Each value can be one of a number of types: an object, an array, a string, a number, the Boolean values TRUE
or FALSE
, or NULL
(indicating a lack of a value).
Using JSON
The json extension, included by default in PHP installations, natively supports converting data to JSON format from PHP variables and vice versa.
To get a JSON representation of a PHP variable, use json_encode()
:
$data
=
array
(
1
,
2
,
"
three
"
);
$jsonData
=
json_encode
(
$data
);
echo
$jsonData
;
[
1
,
2
,
"
three
"
]
Similarly, if you have a string containing JSON data, you can turn it into a PHP variable using json_decode()
:
$jsonData
=
"
[1, 2, [3, 4],
\"
five
\"
]
"
;
$data
=
json_decode
(
$jsonData
);
print_r
(
$data
);
Array
(
[
0
]
=>
1
[
1
]
=>
2
[
2
]
=>
Array
(
[
0
]
=>
3
[
1
]
=>
4
)
[
3
]
=>
five
)
If the string is invalid JSON, or if the string is not encoded in UTF-8 format, a single NULL
value is returned instead.
The value types in JSON are converted to PHP equivalents as follows:
object
- An associative array containing the object’s key-value pairs. Each ...
Get Programming PHP, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.