PHP JSON Complete Tutorial (With Examples) - Alex Web Develop
PHP JSON Complete Tutorial (With Examples) - Alex Web Develop
a DEVELOPERS
d
k
This is the ultimate guide to use JSON objects with PHP.
Plus: working examples you can copy and use right away.
https://alexwebdevelop.com/php-json-backend/ 1/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
d
k CONTENTS
CHAPTER 1
What is JSON?
CHAPTER 2
JSON encoding
2
CHAPTER 3
Encoding options
https://alexwebdevelop.com/php-json-backend/ 2/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
CHAPTER 4
a
CHAPTER 5
JSON decoding
d
k
CHAPTER 6
EXAMPLE
EXAMPLE
2
Chapter 1
What is JSON?
https://alexwebdevelop.com/php-json-backend/ 3/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
d
k
What is JSON?
https://alexwebdevelop.com/php-json-backend/ 4/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
"Name": "Alex",
"Age": 37,
"Admin": true,
"Contact": {
"Site": "alexwebdevelop.com",
"Phone": 123456789,
"Address": null
},
"Tags": [
"php",
"web",
"dev"
]
a }
d
k
https://alexwebdevelop.com/php-json-backend/ 5/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
integers or oats.
a A value can also be a JSON object itself, containing more
d nested key => values.
https://alexwebdevelop.com/php-json-backend/ 6/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
Note:
https://alexwebdevelop.com/php-json-backend/ 7/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
[
"Apple",
"Orange",
"Kiwi"
]
https://alexwebdevelop.com/php-json-backend/ 8/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
<Element>
<Name>Alex</Name>
<Age>37</Age>
<Admin>true</Admin>
<Contact>
<Site>alexwebdevelop.com</Site>
<Phone>123456789</Phone>
<Address></Address>
</Contact>
<Tags>
<Tag>php</Tag>
<Tag>web</Tag>
<Tag>dev</Tag>
a </Tags>
</Element>
d
k JSON is much more readable, isn’t it?
For example:
and more
https://alexwebdevelop.com/php-json-backend/ 9/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
service.
a
d Chapter 2
JSON encoding
k
Creating a JSON object with PHP is simple:
https://alexwebdevelop.com/php-json-backend/ 10/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
';
The reason is that PHP arrays are a perfect match for the
JSON structure: each PHP array key => value pair becomes
a key => value pair inside the JSON object.
2
For example:
https://alexwebdevelop.com/php-json-backend/ 11/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
echo $json;
a
d {"Product":"Coffee","Price":1.5}
k
chapter.
https://alexwebdevelop.com/php-json-backend/ 12/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
/* The JSON string created from the array, using the J
$json = json_encode($array, JSON_PRETTY_PRINT);
d echo '<pre>';
echo $json;
k echo '</pre>';
{
"Product": "Coffee",
"Price": 1.5
}
For example:
echo '<pre>';
a
echo $json;
echo '</pre>';
d
k This time, the output is a JSON array ( note the square
brackets and the fact that there are no keys):
[
"Coffee",
"Chocolate",
"Tea"
]
You can create nested JSON objects and arrays using PHP
multi-dimensional arrays.
For example, this is how you can create the rst example:
$array = array();
2
$array['Name'] = 'Alex';
$array['Age'] = 37;
$array['Admin'] = TRUE;
https://alexwebdevelop.com/php-json-backend/ 14/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
$array['Contact'] = array
(
'Site' => "alexwebdevelop.com",
'Phone' => 123456789,
'Address' => NULL
);
echo '<pre>';
echo $json;
a echo '</pre>';
d
k
To recap:
PHP associative arrays become JSON objects.
(The key => values of the PHP array become the key =>
objects or arrays.
Chapter 3
Encoding options
2
json_encode() supports 15 different encoding options.
https://alexwebdevelop.com/php-json-backend/ 15/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
In this chapter, I’m going to show you the ones you need to
know and explain how they work (with examples).
a
d
k The json_encode() function takes the variable to encode as
rst argument and a list of encoding options as second
argument.
There are 15 different options you can use. Let’s look at the
most useful ones.
"Product": "Coffee",
https://alexwebdevelop.com/php-json-backend/ 16/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
"Price": 1.5
{"Product":"Coffee","Price":1.5}
a
d
Of course, spaces do matter if they are inside variables.
{
"Name 1": "My Name",
"Name 2": "MyName"
}
https://alexwebdevelop.com/php-json-backend/ 17/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
All right.
a JSON_FORCE_OBJECT
With this option, PHP arrays are always encoded into JSON
objects regardless of their type.
echo '</pre>';
echo $json;
echo '</pre>':
[
"Apple",
"Banana",
https://alexwebdevelop.com/php-json-backend/ 18/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
"Coconut"
]
d echo '<pre>';
echo $json;
echo '</pre>';
k
{
"0": "Apple",
"1": "Banana",
"2": "Coconut"
}
You can see that the keys are strings because they are
enclosed by double quotes.
2
JSON_INVALID_UTF8_SUBSTITUTE
https://alexwebdevelop.com/php-json-backend/ 19/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
JSON_INVALID_UTF8_IGNORE
JSON_PARTIAL_OUTPUT_ON_ERROR
For example:
a
d /* This generates an invalid character. */
$invalidChar = chr(193);
k $array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3"
$json = json_encode($array, JSON_PRETTY_PRINT);
https://alexwebdevelop.com/php-json-backend/ 20/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
This way, you can get a valid JSON object even if there are
invalid characters somewhere:
$invalidChar = chr(193);
$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3"
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_IN
a }
else
d
{
echo '<pre>';
echo $json;
k }
echo '</pre>';
{
"Key 1": "A",
"Key 2": "B",
"Key 3": "ufffd"
}
2
$invalidChar = chr(193);
$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3"
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_IN
https://alexwebdevelop.com/php-json-backend/ 21/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a {
"Key 1": "A",
k }
$invalidChar = chr(193);
$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3"
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_PA
https://alexwebdevelop.com/php-json-backend/ 22/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
{
"Key 1": "A",
"Key 2": "B",
"Key 3": null
}
JSON_NUMERIC_CHECK
$array = array(
'String' => 'a string',
'Numeric string 1' => '0',
'Numeric string 2' => '1234',
'Numeric string 3' => '1.103',
'Numeric string 4' => '-0.3',
'Numeric string 5' => '5e12'
);
echo '<pre>';
echo $json;
echo '</pre>'; 2
{
"String": "a string",
https://alexwebdevelop.com/php-json-backend/ 23/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
As you can see, all the values are strings (in double quotes).
d $array = array(
k
'String' => 'a string',
'Numeric string 1' => '0',
'Numeric string 2' => '1234',
'Numeric string 3' => '1.103',
'Numeric string 4' => '-0.3',
'Numeric string 5' => '5e12'
);
echo '<pre>';
echo $json;
echo '</pre>';
{
"String": "a string",
"Numeric string 1": 0,
"Numeric string 2": 1234,
"Numeric string 3": 1.103,
"Numeric string 4": -0.3,
"Numeric string 5": 5000000000000
}
2
https://alexwebdevelop.com/php-json-backend/ 24/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
JSON_THROW_ON_ERROR
So, if you have an older PHP version it will not work for you.
a errors” chapter.
d There are a few more json_encode() options.
k However, they are more speci c, and you will probably
never use them.
Chapter 4
The next step is to send your JSON object to a front-end
application or to a remote service.
2
In this chapter I’m going to show you exactly how to do that.
https://alexwebdevelop.com/php-json-backend/ 25/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
d
You can do that either as a reply to a remote request, or as
a direct HTTP request.
k
Sending a JSON object as a reply to a remote
request
k
Important:
echo $json;
You must not send anything else other than the content-
type header and the $json string.
Sending a JSON object as a direct HTTP request
a
d
k
storage space
https://alexwebdevelop.com/php-json-backend/ 28/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
applications
and so on.
a cURL library.
d
First, you need to initialize a cURL session with curl_init(),
using the service URL as parameter:
k
/* The remote service URL. */
$url = 'https://remote-service.com';
request;
2
Like this:
https://alexwebdevelop.com/php-json-backend/ 29/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
/* Send the request. */
curl_exec($curl);
d
k
{
"snippet": {
"parentId": "YOUR_COMMENT_THREAD_ID",
"textOriginal": "This is the original comment."
}
}
$comment['snippet'] = array(
d $curl = curl_init($url);
k
/* Tell cURL to send a POST request. */
curl_setopt($curl, CURLOPT_POST, TRUE);
Chapter 5
JSON decoding
2
You know how to create and send JSON objects from your
PHP script.
https://alexwebdevelop.com/php-json-backend/ 31/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
d
k JSON is a data interchange format.
In fact, most of the time you will receive a JSON object rst
and then send a JSON object as a reply.
2
Here is how it works.
https://alexwebdevelop.com/php-json-backend/ 32/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
$json =
'
{
"Name": "Alex",
"Age": 37,
"Admin": true,
"Contact": {
"Site": "alexwebdevelop.com",
"Phone": 123456789,
"Address": null
},
"Tags": [
a "php",
"web",
d ]
"dev"
k
}
';
or false)
$jsonData = json_decode($json);
echo '<pre>';
var_dump($jsonData);
echo '</pre>';
a
d The output from the above code shows how the PHP object
k is created:
object(stdClass)#1 (5) {
["Name"]=>
string(4) "Alex"
["Age"]=>
int(37)
["Admin"]=>
bool(true)
["Contact"]=>
object(stdClass)#2 (3) {
["Site"]=>
string(18) "alexwebdevelop.com"
["Phone"]=>
int(123456789)
["Address"]=>
NULL
}
["Tags"]=>
array(3) {
[0]=>
string(3) "php"
[1]=> 2
string(3) "web"
[2]=>
string(3) "dev"
}
https://alexwebdevelop.com/php-json-backend/ 34/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
$jsonData = json_decode($json);
echo $jsonData->Age;
a
d 37
k
Note:
In the output, you can see how the “Tags” JSON array
becomes a PHP numeric array.
$jsonData = json_decode($json);
https://alexwebdevelop.com/php-json-backend/ 35/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
The reason is that JSON keys can contain any valid UTF8
characters, unlike PHP variable names. For example, PHP
variables cannot contain the dash “-” character.
a $json =
'
d {
"Invalid-php-name": "Variable content"
k }
';
$jsonData = json_decode($json);
echo $jsonData->{'Invalid-php-name'};
json_decode() options
2
Let’s see again the rst JSON example.
https://alexwebdevelop.com/php-json-backend/ 36/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
echo '<pre>';
var_dump($jsonData);
echo '</pre>';
The output from the above code shows how the PHP
associative array is created:
a
d
array(5) {
["Name"]=>
string(4) "Alex"
k ["Age"]=>
int(37)
["Admin"]=>
bool(true)
["Contact"]=>
array(3) {
["Site"]=>
string(18) "alexwebdevelop.com"
["Phone"]=>
int(123456789)
["Address"]=>
NULL
}
["Tags"]=>
array(3) {
[0]=>
string(3) "php"
[1]=>
string(3) "web"
[2]=>
string(3) "dev"
}
}
2
You can access the elements just like any array element:
https://alexwebdevelop.com/php-json-backend/ 37/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
Note that JSON arrays are still decoded into PHP numeric
arrays, just like in the previous case.
a Again, you can see from the output that the “Tags” element
is a PHP numeric array.
d
k More decoding options
JSON_OBJECT_AS_ARRAY
JSON_THROW_ON_ERROR
https://alexwebdevelop.com/php-json-backend/ 38/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
JSON_INVALID_UTF8_IGNORE
a
This option works as for json_encode().
$invalidChar = chr(193);
$json =
'
{
"Valid char": "a",
"Invalid char": "' . $invalidChar . '"
}
';
echo '<pre>';
var_dump($jsonData);
echo '</pre>';
NULL
2
https://alexwebdevelop.com/php-json-backend/ 39/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
$invalidChar = chr(193);
$json =
'
{
"Valid char": "a",
"Invalid char": "' . $invalidChar . '"
a }
';
k echo '<pre>';
var_dump($jsonData);
echo '</pre>';
array(2) {
["Valid char"]=>
string(1) "a"
["Invalid char"]=>
string(0) ""
}
JSON_BIGINT_AS_STRING
For example:
https://alexwebdevelop.com/php-json-backend/ 40/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
$json =
'
{
"Small number": 10,
"Big number": 1234567890123456789
}
';
echo '<pre>';
var_dump($jsonData);
a echo '</pre>';
d
k You can see how, in the output array, the big integer is
decoded into a oat and some precision is lost:
array(2) {
["Small number"]=>
int(10)
["Big number"]=>
float(1.2345678901235E+18)
}
$json =
'
{
"Small number": 10,
2
"Big number": 1234567890123456789
}
';
echo '<pre>';
var_dump($jsonData);
echo '</pre>';
array(2) {
["Small number"]=>
int(10)
["Big number"]=>
string(19) "1234567890123456789"
a
}
d
k Chapter 6
https://alexwebdevelop.com/php-json-backend/ 42/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
d
A JSON string received from a remote source is not safe
until you validate it.
k This is true for JSONs received from the request string, like
front-end apps requests, as well as for those received from
remote services.
errors.
https://alexwebdevelop.com/php-json-backend/ 43/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
Like this:
$jsonData = json_decode($json);
a if (is_null($jsonData))
{
d }
echo 'Error decoding JSON.';
k
Note:
For example, the following code will print the error message:
if (!$jsonData)
{
echo 'Error decoding JSON.';
}
2
https://alexwebdevelop.com/php-json-backend/ 44/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
If the decode fails, you can get the error code using the
json_last_error() function, and the error message using the
json_last_error_msg() function:
if (is_null($jsonData))
{
echo 'Error decoding JSON.<br>';
echo 'Error number: ' . json_last_error() . '<br>';
echo 'Error message: ' . json_last_error_msg();
}
a
d
k JSON Exceptions
You can get the error code and message directly from the
JsonException object.
Here is an example:
}
"Invalid element (no value)"
2
';
try
{
$jsonData = json_decode($json, FALSE, 512, JSON_THROW_
https://alexwebdevelop.com/php-json-backend/ 45/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
}
catch (JsonException $je)
{
echo 'Error decoding JSON.<br>';
echo 'Error number: ' . $je->getCode() . '<br>';
echo 'Error message: ' . $je->getMessage();
}
{
"Name": "Irish coffee",
"Price": 2.5
}
After you have decoded the JSON string into a PHP object
or array, you need to check that:
a }
die();
k if (!isset($jsonArray['Name']))
{
echo 'Error: "Name" not set.';
die();
}
https://alexwebdevelop.com/php-json-backend/ 47/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
d
{
echo 'Error: "Price" is not a number.';
die();
k }
Note:
Example
2
Create a JSON object from database data
https://alexwebdevelop.com/php-json-backend/ 48/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
You will often need to use that data to create your JSON
objects.
a
d
k
In this example, you are going to write a simple PHP script
that returns information about a music album.
{
"Title": "Aqualung",
"Artist": "Jethro Tull",
"Year": 1971,
"Duration": 2599,
"Tracks": [
"Aqualung",
"Cross-Eyed Mary",
"Cheap Day Return",
"Mother Goose",
2
"Wond'ring Aloud",
"Up to Me",
"My God",
"Hymn 43",
"Slipstream",
https://alexwebdevelop.com/php-json-backend/ 49/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
"Locomotive Breath",
"Wind-Up"
]
}
albums table
tracks table
If you want to know more about PHP and MySQL, you can
refer to this complete tutorial:
/* Connection step. */
try
{
$pdo = new PDO($dsn, 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EX
a }
catch (PDOException $e)
d
{
die();
}
k
Now, you need to create the PHP associative array that will
be encoded into the JSON object:
/* The PHP array with the data for the JSON object. */
$data = array();
Once you have the query result, you can get the album title,
artist, and year.
https://alexwebdevelop.com/php-json-backend/ 51/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a try
{
d
$albumRes = $pdo->prepare($albumQuery);
$albumRes->execute($albumParams);
}
$albumRow = $albumRes->fetch(PDO::FETCH_ASSOC);
You will need to add all the track names to the “Tracks”
JSON array. 2
Note: since “Tracks” is a JSON array, you need to use a PHP
numeric array.
https://alexwebdevelop.com/php-json-backend/ 52/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
$data['Tracks'] = array();
d */
Note: the result is ordered by track number.
try
{
$tracksRes = $pdo->prepare($tracksQuery);
$tracksRes->execute($tracksParams);
}
catch (PDOException $e)
{
die();
}
2
https://alexwebdevelop.com/php-json-backend/ 53/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a Example
d
Send a JSON le as an email attachment
k
In this last example, you will:
Let’s start with the JSON string from the previous example:
2
$json =
'
{
"Title": "Aqualung",
https://alexwebdevelop.com/php-json-backend/ 54/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a "Locomotive Breath",
"Wind-Up"
d }
]
k
';
2. De ne the le name.
De ne the le path
https://alexwebdevelop.com/php-json-backend/ 55/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
a
d De ne the le name and save the le
/* Save OK. */
echo 'JSON file successfully saved.';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
https://alexwebdevelop.com/php-json-backend/ 57/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
d try
{
k
/* Send the mail. */
$mail->send();
}
catch (Exception $e)
{
/* PHPMailer exception. */
echo $e->errorMessage();
die();
}
Conclusion
N
In this tutorial, you learned everything you need to use JSON
objects with PHP.
https://alexwebdevelop.com/php-json-backend/ 58/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
Copyright notice
The images used in this post have been downloaded from Freepik.
26 1 0
a 16 Comments
d Scribe on June 24, 2020 at 3:07 pm
k Thanks for the guide Alex. This has been very helpful!
Reply
Thank you Scribe, I’m glad this tutorial has been helpful
to you!
Reply
Reply
Reply
https://alexwebdevelop.com/php-json-backend/ 59/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
Reply
Thank you.
Reply
Reply
Reply
https://alexwebdevelop.com/php-json-backend/ 60/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
Thanks Uzor
Reply
Reply
Reply
Hey Jan,
you are right. That was a typo. I just xed it.
Thanks!
Reply
2
Sam on May 31, 2020 at 4:27 pm
Reply
https://alexwebdevelop.com/php-json-backend/ 61/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
py
Hi Sam,
the older version is no longer online since this new one is
far more complete.
Is there something you need from the older article?
Reply
a
d This website and its content is copyright of Alessandro Castellano. All rights reserved.
https://alexwebdevelop.com/php-json-backend/ 62/62