Skip to Main Content
Programming PHP, 4th Edition
book

Programming PHP, 4th Edition

by Kevin Tatroe, Peter MacIntyre
March 2020
Intermediate to advanced content levelIntermediate to advanced
542 pages
12h 22m
English
O'Reilly Media, Inc.
Book available
Content preview from Programming PHP, 4th Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 9781492054122Errata PageSupplemental Content