0% found this document useful (0 votes)
51 views62 pages

PHP JSON Complete Tutorial (With Examples) - Alex Web Develop

how to use json in php with examples

Uploaded by

riris sigit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
51 views62 pages

PHP JSON Complete Tutorial (With Examples) - Alex Web Develop

how to use json in php with examples

Uploaded by

riris sigit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

PHP JSON COMPLETE


TUTORIAL
THE DEFINITIVE JSON GUIDE FOR PHP

a DEVELOPERS

d
k
This is the ultimate guide to use JSON objects with PHP.

In this tutorial (updated in 2020) I’ll show you:

How to create and send JSON objects


How to decode JSON objects
All the encoding options explained
How to set the JSON Content-Type

JSON validation… and more

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

Sending a JSON object

a
CHAPTER 5

JSON decoding

d
k
CHAPTER 6

Validation and errors

EXAMPLE

Create a JSON object from database data

EXAMPLE

Send a JSON le as an email attachment

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

You have heard of JSON before.

But what is it, exactly?

And what is it used for?

In this rst chapter, I’m going to explain how JSON works


and what are its uses in web development.

a
d
k

What is JSON?

JSON is a data container used to send, receive and store


variables.

As Wikipedia de nes it, JSON is a “data interchange


format”.

Many web applications use this data format to exchange


data over the Internet.
2
This is how a JSON object looks like:

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  

As you can see, a JSON object is a container for other


variables.

More precisely, a JSON object contains a list of key => value


pairs, separated by a colon.

The keys are the names of the variables.

In the above example, the keys are “Name”, “Age”, “Admin”,


“Contact” and “Tags”.

The keys are always strings and are always enclosed in


double quotes.

The values are the actual values of the variables identi ed


by the keys.
2
While the keys are always strings, the values can be any of
the following types:

Strings, like “Alex” (the Name variable).

https://alexwebdevelop.com/php-json-backend/ 5/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Numbers, like 37 (the Age variable). Numbers can be

integers or oats.

Boolean values (“true” or “false”), like the Admin variable.

Null values, like the Address variable.

Strings are always enclosed in double quotes (“”). Numbers,


Booleans and null values are not.

 
a A value can also be a JSON object itself, containing more
d nested key => values.

k In other words, a JSON object can contain one or more JSON


objects.

For example, the “Contact” variable is a JSON object with


the following key => value pairs:

“Site” (key) => “alexwebdevelop.com” (value)

“Phone” (key) => 123456789 (value)

“Address” (key) => null (value)

Objects are enclosed by curly brackets: “{ }”.

Note that the whole JSON is an object itself, so it is enclosed


by curly brackets too.

https://alexwebdevelop.com/php-json-backend/ 6/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

a  

d There is one more possible type: JSON arrays.

k A JSON array is a list of ordered, unnamed elements. In


other words, a list of values without keys.

The “Tags” variable in the previous example is a JSON array.

Arrays are enclosed by square brackets: “[ ]”.

JSON objects and arrays can contain any number of


elements, including other objects and arrays.

The above example is simple, but JSON structures can also


be very complex with tens or hundreds of nested elements.

Note:

A JSON array is a perfectly valid JSON by itself, even if it is 2


not inside an object.

For example, this is a valid JSON:

https://alexwebdevelop.com/php-json-backend/ 7/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

[
"Apple",
"Orange",
"Kiwi"
]

How can you use JSON?


a JSON is very popular among web developers. Indeed, most

d of today’s web applications use JSON to send and receive


data.
k For example, libraries like Angular.JS and Node.JS use JSON
to exchange data with the back-end.

One of the reasons why JSON is widely used is because it is


very lightweight and easy to read.

Indeed, when you look at the previous JSON example, you


can easily understand how the data is structured.

As a comparison, this is how the same data is represented in 2


the more complex XML format:

<?xml version="1.0" encoding="UTF-8"?>

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?

So, JSON is the format used by front-end apps and by back-


end systems (including PHP) to talk to each other.

But JSON has other uses, too.

For example:

exchange data over the Internet between HTTP services

use online platforms like cloud services, SMS gateways

and more

create modern APIs for your clients

Therefore, it’s important for a PHP developer like you to


learn how to handle it. 2
The good news is: it’s really easy.

https://alexwebdevelop.com/php-json-backend/ 9/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

There are three basic operations you need to learn:

1. Create (or encode) a JSON object.

2. Send a JSON object to a front-end app or to a remote

service.

3. Decode a JSON object received by your PHP script.

Let’s start with the encoding step.

a
d Chapter 2

JSON encoding
k
Creating a JSON object with PHP is simple:

You just need to use the json_encode() function.

Let’s see how to do it in practice with a few examples.

In PHP, JSON objects are string variables.

https://alexwebdevelop.com/php-json-backend/ 10/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

So, in theory, you could create a JSON string like this:

/* A JSON object as a PHP string. */


$json =
'
{
"Name": "Alex",
"Age": 37,
"Admin": true
}

a
';

d However, creating a JSON string like that is not very handy.


k Especially if the JSON structure is complex.

Fortunately, you don’t have to do that.

A much better solution is to encode a PHP variable into a


JSON object using the json_encode() function.

json_encode() takes care of building the JSON structure for


you and returns the JSON object as a string.

The best way to create a JSON object is to start from a PHP


array.

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

/* The PHP array. */


$array = array("Product" => "Coffee", "Price" => 1.5);

/* The JSON string created from the array. */


$json = json_encode($array);

echo $json;

The $json variable looks like this:

a
d {"Product":"Coffee","Price":1.5}

k
 

json_encode() takes three arguments:

1. The variable to be encoded as a JSON object. ($array, in

the previous example).

2. A list of encoding options, which we will cover in the next

chapter.

3. The maximum nesting depth of the JSON. You can ignore

this, unless you need to work with huge JSON objects.

You will learn about the encoding options in the next


chapter.
2
But there is one option that I want you to use
now: JSON_PRETTY_PRINT.

https://alexwebdevelop.com/php-json-backend/ 12/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

This option makes the output JSON more readable by


adding some spaces. This way, you can print it nicely within
<pre> tags and make it easier to read.

This is how it works:

/* The PHP array. */


$array = array("Product" => "Coffee", "Price" => 1.5);

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>';

Now, the output is more human-friendly:

{
"Product": "Coffee",
"Price": 1.5
}

Associative and numeric arrays

PHP associative arrays are encoded into JSON objects, like


in the above example.

The elements of the PHP array become the elements of the


2
JSON object.

If you want to create JSON arrays instead, you need to use


PHP numeric arrays.
https://alexwebdevelop.com/php-json-backend/ 13/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

For example:

/* A PHP numeric array. */


$array = array("Coffee", "Chocolate", "Tea");

/* The JSON string created from the array. */


$json = json_encode($array, JSON_PRETTY_PRINT);

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
);

$array['Tags'] = array('php', 'web', 'dev');

$json = json_encode($array, JSON_PRETTY_PRINT);

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 =>

values of the JSON object.)

PHP numeric arrays becomes JSON arrays.

PHP multi-dimensional arrays become nested JSON

objects or arrays.

Chapter 3

Encoding options

2
json_encode() supports 15 different encoding options.

Don’t worry… you don’t need to know them all.

https://alexwebdevelop.com/php-json-backend/ 15/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

But some of them can be useful.

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.

You already used an encoding option in the last chapter:


JSON_PRETTY_PRINT.

This option adds some white spaces in the JSON string, so


that it becomes more readable when printed.

White spaces, as well as other “blank” characters like tabs


and newlines, have no special meaning inside a JSON
object.

In other words, this:


2

"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

has exactly the same value as this:

{"Product":"Coffee","Price":1.5}

a
d
Of course, spaces do matter if they are inside variables.

For example, the “Name 1” and “Name 2” variables in the


k following JSON are different:

{
"Name 1": "My Name",
"Name 2": "MyName"
}

If you want to use more options together, you need to


separate them with a “|“.

(The technical reason is that the option argument is actually


a bitmask).

For example, this is how you can use the


JSON_PRETTY_PRINT, JSON_FORCE_OBJECT
and JSON_THROW_ON_ERROR options together: 2

$array = array('key 1' => 10, 'key 2' => 20);

https://alexwebdevelop.com/php-json-backend/ 17/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

$json = json_encode($array, JSON_PRETTY_PRINT | JSON_FO

All right.

Now let’s look at the other json_encode() options.

a JSON_FORCE_OBJECT

d Remember how PHP associative arrays are encoded into

k JSON objects, while numeric arrays are encoded into JSON


arrays?

With this option, PHP arrays are always encoded into JSON
objects regardless of their type.

By default, without this option, if you encode a numeric


array you get a JSON array:

/* A PHP numeric array. */


$fruits = array('Apple', 'Banana', 'Coconut');

$json = json_encode($fruits , JSON_PRETTY_PRINT);

echo '</pre>';
echo $json;
echo '</pre>':

This is the output: 2

[
"Apple",
"Banana",

https://alexwebdevelop.com/php-json-backend/ 18/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

"Coconut"
]

But if you use the JSON_FORCE_OBJECT option, the


numeric array is encoded as a JSON object like this:

/* A PHP numeric array. */


$fruits = array('Apple', 'Banana', 'Coconut');

a $json = json_encode($fruits , JSON_PRETTY_PRINT | JSON_

d echo '<pre>';
echo $json;
echo '</pre>';

k
{
"0": "Apple",
"1": "Banana",
"2": "Coconut"
}

This option comes in handy when working with front-end


apps or web services that accept JSON objects only.

The PHP array numeric keys (in this case:  0, 1 and 2)


become the keys of JSON object.

But remember: JSON objects keys are always strings, even


when they are created from a numeric array like in this case.

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

JSON expects the strings to be encoded in UTF-8.

If you try encoding a string with invalid UTF-8 characters,


json_encode() will fail and will return FALSE instead of the
JSON string.

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);

if ($json === FALSE)


{
echo 'Warning: json_encode() returned FALSE.';
}
else
{
echo '<pre>';
echo $json;
echo '</pre>';
}

Warning: json_encode() returned FALSE.

If you set the JSON_INVALID_UTF8_SUBSTITUTE option, all 2


invalid characters are replaced by a special “replacement”
UTF8 character: “ufffd”.

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

if ($json === FALSE)


{
echo 'Warning: json_encode() returned FALSE.';

a }
else

d
{
echo '<pre>';
echo $json;

k }
echo '</pre>';

{
"Key 1": "A",
"Key 2": "B",
"Key 3": "ufffd"
}

The JSON_INVALID_UTF8_IGNORE option has a similar


effect.

The only difference is that the invalid characters are


completely removed instead of being replaced:

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

if ($json === FALSE)


{
echo 'Warning: json_encode() returned FALSE.';
}
else
{
echo '<pre>';
echo $json;
echo '</pre>';
}

a {
"Key 1": "A",

d "Key 2": "B",


"Key 3": ""

k }

JSON_PARTIAL_OUTPUT_ON_ERROR is similar, too.

This option replaces invalid characters with NULL:

$invalidChar = chr(193);

$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3"
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_PA

if ($json === FALSE)


{
echo 'Warning: json_encode() returned FALSE.';
}
else
{
echo '<pre>';
echo $json;
2
echo '</pre>';
}

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

a By default, all PHP strings are encoded as strings in the


d JSON object.

k When the JSON_NUMERIC_CHECK option is set,


json_encode() automatically encodes PHP numeric strings
into JSON numbers instead of strings.

The following example shows the difference.

This is the default behavior:

$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'
);

$json = json_encode($array , JSON_PRETTY_PRINT);

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

"Numeric string 1": "0",


"Numeric string 2": "1234",
"Numeric string 3": "1.103",
"Numeric string 4": "-0.3",
"Numeric string 5": "5e12"
}

As you can see, all the values are strings (in double quotes). 

If you set the JSON_NUMERIC_CHECK option, integer and

a oat numeric strings become JSON numbers:

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'
);

$json = json_encode($array , JSON_PRETTY_PRINT | JSON_N

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

This option is available as of PHP 7.3.0.

So, if you have an older PHP version it will not work for you.

This option makes json_encode() throw a JsonException if


an error occurs.

You will see how it works in practice in the “Validation and

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.

Feel free to ask me about them in the comments if you want


more details.

Chapter 4

Sending a JSON object

Now you know how to create a JSON object from a PHP


array.

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

If you are creating a JSON object, it’s because you need to

a send it to a front-end application or to a remote service.

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

This is the case when your PHP script receives a remote


request and must reply with a JSON object.

For example, when a front-end app ( running on the remote


user’s browser) sends a request to your PHP back-end,
or when a remote HTTP service connects to your API script
to retrieve some data. 2
 

When your PHP back-end receives the request, it prepares


the response data and encodes it into a JSON object (as you
https://alexwebdevelop.com/php-json-backend/ 26/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

have learned in the previous chapters).

To send the JSON object as a reply to the remote caller, you


need to:

1. Set the JSON HTTP content-type: application/json.

2. Return the JSON as a string.

To set the content-type, you need to use the PHP header()


function. Like this:
a
d header('Content-Type: application/json');

k
Important:

You must call header() before sending any output to the


browser.

That means that you cannot execute any echo statement


before header(), and there must be no HTML code before
the <?php tag. Empty lines are not allowed either.

After setting the content-type, you can return the JSON


string:

/* Set the content-type. */


header('Content-Type: application/json');

/* The array with the data to return. */


$array = array("Coffee", "Chocolate", "Tea");
2
/* The JSON string created from the array. */
$json = json_encode($array);

/* Return the JSON string. */


https://alexwebdevelop.com/php-json-backend/ 27/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

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
 

In the previous scenario, a front-end app or a remote service


connects to your PHP back-end. Then, your back-end sends
the JSON object as a reply.

In other contexts, your PHP script must be the rst to send


the JSON object.

In such cases, you need to open an HTTP connection and


send the JSON data along with it.

You need to open a direct HTTP connection when you want


to use a remote service, for example: 2
when sending data to a cloud service such as an online

storage space

https://alexwebdevelop.com/php-json-backend/ 28/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

when using a service provider like a SMS gateway

when using APIs provided by social networks or SAAS

applications

and so on.

You can handle outbound HTTP connections using the PHP

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';

/* The cURL session. */


$curl = curl_init($url);

Next, you need to set some cURL parameters with the


curl_setopt() function:

CURLOPT_POST, to tell cURL to send a POST HTTP

request;

CURLOPT_POSTFIELDS, to set the JSON object as the

POST request content;

CURLOPT_HTTPHEADER, to set the JSON content-type.

2
Like this:

/* Tell cURL to send a POST request. */


curl_setopt($curl, CURLOPT_POST, TRUE);

https://alexwebdevelop.com/php-json-backend/ 29/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

/* Set the JSON object as the POST content. */


curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

/* Set the JSON content-type: application/json. */


curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-T

Finally, you can send the request with curl_exec():

a
/* Send the request. */
curl_exec($curl);

d
k  

For example, YouTube provides a data API to perform


operations through HTTP calls.

One of such operations is to post a comment reply.

To do that, you need to send the following JSON object:

{
"snippet": {
"parentId": "YOUR_COMMENT_THREAD_ID",
"textOriginal": "This is the original comment."
}
}

Here is an example of how to do that.

(The YouTube API requires some authentication steps that 2


are not reported here.)

/* Create the array with the comment data. */


$comment = array();
https://alexwebdevelop.com/php-json-backend/ 30/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

$comment['snippet'] = array(

"parentId" => "YOUR_COMMENT_THREAD_ID",


"textOriginal" => "This is the original comment."
);

/* Encode it into a JSON string. */


$json = json_encode($comment);

/* The YouTube API URL. */


$url = "https://www.googleapis.com/youtube/v3/comments

a /* The cURL session. */

d $curl = curl_init($url);

k
/* Tell cURL to send a POST request. */
curl_setopt($curl, CURLOPT_POST, TRUE);

/* Set the JSON object as the POST content. */


curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

/* Set the JSON content-type: application/json. */


curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-T

/* Send the request. */


$return = curl_exec($curl);

/* Print the API response. */


echo $return;

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

In this chapter, you are going to learn how to decode the


JSON objects that your PHP application receives.

a
d
k JSON is a data interchange format.

Just like you can send JSON objects to a front-end app or to


a remote service, you can receive JSON objects from them
as well.

In fact, most of the time you will receive a JSON object rst
and then send a JSON object as a reply.

After you receive a JSON object, you need to decode it to


access the variables contained inside.

To do that, you need to use the json_decode() function.

json_decode(), as its name suggests, decodes a JSON string


into a PHP object or array. All the variables contained in the
JSON object will be available in the PHP object or array.

  2
Here is how it works.

Let’s take our rst JSON object example:

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
}
';

As long as the JSON is a string, there is no easy way to


access all the variables contained in it.

This is where json_decode() comes into play.

By using json_decode(), you will be able to access all the


variables as object properties or array elements.

By default, json_decode() returns a generic PHP object.

Each JSON variable is decoded according to these rules:

JSON objects become PHP objects

JSON arrays become PHP numeric arrays 2


JSON strings become PHP strings

JSON numbers become PHP integers or oats

JSON null values become PHP null values


https://alexwebdevelop.com/php-json-backend/ 33/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

JSON Boolean values become PHP Boolean values (true

or false)

For example (using the above JSON):

$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

So, if you want to access the “Age” element of the JSON


object, you can do it like this:

$jsonData = json_decode($json);

echo $jsonData->Age;

a
d 37

k
 

Note:

JSON objects are decoded into PHP objects. However, JSON


arrays are decoded into PHP numeric arrays.

In the output, you can see how the “Tags” JSON array
becomes a PHP numeric array.

Since “Tags” is a numeric array, you can iterate through


its element using a foreach loop, like this:

$jsonData = json_decode($json);

foreach ($jsonData->Tags as $tag)


{
echo $tag . "<br>";
} 2

https://alexwebdevelop.com/php-json-backend/ 35/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

In some cases, the names of the JSON variables cannot be


used as names for PHP variables.

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.

In these cases, you can access the variable inside the


decoded object using this syntax:

a $json =
'

d {
"Invalid-php-name": "Variable content"

k }
';

$jsonData = json_decode($json);

echo $jsonData->{'Invalid-php-name'};

json_decode() options

The rst json_decode() argument is the JSON string.

The second argument is a Boolean option called $assoc.

If this parameter is set to true, json_decode() decodes JSON


objects into PHP associative arrays instead of PHP objects.

 
2
Let’s see again the rst JSON example.

This time, we set the the $assoc option to true:

https://alexwebdevelop.com/php-json-backend/ 36/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

/* The second argument is set to true. */


$jsonData = json_decode($json, TRUE);

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

$jsonData = json_decode($json, TRUE);

echo 'Name is: ' . $jsonData['Name'];

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

The third json_decode() argument is the recursion depth. Its


default value is 512 and you can safely ignore it.

The fourth and last argument is a list of options, much like


the second json_encode() argument. In fact, some of the
options are the same.

Let’s take a quick look.

JSON_OBJECT_AS_ARRAY

This option has the same effect as setting the $assoc


argument to true. It makes json_decode() return PHP
associative arrays instead of PHP objects.
2
 

JSON_THROW_ON_ERROR

https://alexwebdevelop.com/php-json-backend/ 38/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

This option makes json_decode() throw a JsonException if


an error occurs.

You will see how it works in practice in the “Validation and


errors” chapter.

JSON_INVALID_UTF8_IGNORE

a
This option works as for json_encode().

Normally, if the source JSON string contains an invalid


d character, json_decode() returns NULL.

k For example, if you put an invalid UTF-8 character in the


JSON string and you try decoding it, you get NULL in return:

$invalidChar = chr(193);

$json =
'
{
"Valid char": "a",
"Invalid char": "' . $invalidChar . '"
}
';

$jsonData = json_decode($json, TRUE);

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

Enabling the JSON_INVALID_UTF8_IGNORE option makes


json_decode() ignore invalid characters:

$invalidChar = chr(193);

$json =
'
{
"Valid char": "a",
"Invalid char": "' . $invalidChar . '"

a }
';

d $jsonData = json_decode($json, TRUE, 512, JSON_INVALID_

k echo '<pre>';
var_dump($jsonData);
echo '</pre>';

array(2) {
["Valid char"]=>
string(1) "a"
["Invalid char"]=>
string(0) ""
}

JSON_BIGINT_AS_STRING

This option is useful when the JSON object contains very


large integers.
2
When an integer exceeds the maximum PHP size, it is
converted into a oat and some precision is lost.

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
}
';

$jsonData = json_decode($json, TRUE);

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)
}

The JSON_BIGINT_AS_STRING makes json_decode() turn


big integers into PHP strings, so you can handle them
properly (for example, with the BCMath extension) without
losing precision:

$json =
'
{
"Small number": 10,
2
"Big number": 1234567890123456789
}
';

$jsonData = json_decode($json, TRUE, 512, JSON_BIGINT_A


https://alexwebdevelop.com/php-json-backend/ 41/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

echo '<pre>';
var_dump($jsonData);
echo '</pre>';

array(2) {
["Small number"]=>
int(10)
["Big number"]=>
string(19) "1234567890123456789"

a
}

d
k Chapter 6

Validation and errors

In this chapter you will learn:

How to properly validate JSON objects and variables


How to catch encoding and decoding errors

So, if you want your code to be secure and solid, be sure to


read this chapter.

https://alexwebdevelop.com/php-json-backend/ 42/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Variable validation is crucial for web security.

In your PHP applications, you must validate any untrusted


variable before you can use it.

(This is one of the rst things I teach in my PHP Security


course).

a JSON objects are no exception.

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.

When you receive a JSON object, you need to:

1. Make sure it is a valid JSON string, by checking decoding

errors.

2. Validate each variable contained inside the JSON object.

JSON decoding errors

By default, json_decode() returns NULL if it cannot decode


the provided JSON string. 2
So, to check that the json_decode() argument is a valid
JSON, you can simply check that its return value is not
NULL.

https://alexwebdevelop.com/php-json-backend/ 43/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Like this:

/* An invalid JSON string. */


$json =
'
{
"Invalid element (no value)"
}
';

$jsonData = json_decode($json);

a if (is_null($jsonData))
{

d }
echo 'Error decoding JSON.';

k
Note:

Do not use the “if (!$jsonData)” syntax.

Why? Because if you decode an empty JSON string into an


empty PHP array, this syntax will consider the empty JSON
string as an invalid JSON.

For example, the following code will print the error message:

$json = '{ }';

$jsonData = json_decode($json, TRUE);

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

From PHP version 7.3.0, you can set the


json_decode() JSON_THROW_ON_ERROR option.

This option makes json_decode() throw a JsonException on


errors, instead of returning NULL.

In this case, you need to use the try/catch syntax.

You can get the error code and message directly from the
JsonException object.

Here is an example:

/* An invalid JSON string. */


$json =
'
{

}
"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();
}

a JSON variables validation

d After you have successfully decoded the JSON object, you


need to validate each variable contained in it.

k As an example, suppose that you expect a JSON object with


two variables: a “Name” string variable and a “Price” oat
variable. Like this:

{
"Name": "Irish coffee",
"Price": 2.5
}

After you have decoded the JSON string into a PHP object
or array, you need to check that:

Both the “Name” and “Price” variables are set.

The “Name” variable is a valid string. It must not contain

invalid characters and its length must be valid.

The “Price” variable is a valid oat number. It must be a 2


positive number lower than a maximum value.

Let’s see how it’s done in practice.


https://alexwebdevelop.com/php-json-backend/ 46/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Let’s start from the “Name” variable:

/* Decode the JSON string into a PHP array. */


$jsonArray = json_decode($json, TRUE);

/* Check for decoding errors. */


if (is_null($jsonArray))
{
echo 'Error decoding JSON.<br>';
echo 'Error number: ' . json_last_error() . '<br>';
echo 'Error message: ' . json_last_error_msg();

a }
die();

d /* Check that the "Name" variable is set. */

k if (!isset($jsonArray['Name']))
{
echo 'Error: "Name" not set.';
die();
}

/* Check that Name contains only printable characters.


if (!ctype_print($jsonArray['Name']))
{
echo 'Error: "Name" contains invalid characters.';
die();
}

/* Check the Name length. */


$minLength = 2;
$maxLength = 16;
$nameLength = mb_strlen($jsonArray['Name']);

if (($nameLength < $minLength) || ($nameLength > $maxLe


{
echo 'Error: "Name" is too short or too long.';
die();
}
2

(Of course, the exact validation steps depend on how your


application is going to use the variable).

https://alexwebdevelop.com/php-json-backend/ 47/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

And this is how to validate the “Price” variable:

/* Check that the "Price" variable is set. */


if (!isset($jsonArray['Price']))
{
echo 'Error: "Price" not set.';
die();
}

a /* Check that Price is a float. */


if (!is_numeric($jsonArray['Price']))

d
{
echo 'Error: "Price" is not a number.';
die();

k }

/* Check that Price is positive and less that a maximum


$maxPrice = 1000;

if (($jsonArray['Price'] <= 0) || ($jsonArray['Price']


{
echo 'Error: Price value is not valid.';
die();
}

Note:

If you want to know more about oat numbers validation, I


explain how to properly validate oat variables in this free
lesson from my PHP Security course.

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

Web applications keep their data on the database.

You will often need to use that data to create your JSON
objects.

In this example I’ll show how to do just that.

a
d
k
In this example, you are going to write a simple PHP script
that returns information about a music album.

The information is retrieved from the database and then


returned as a JSON object.

This is how the nal JSON looks like:

{
"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"
]
}

The information is stored in two database tables.

The rst table, named “albums”, contain the album name,


artist, and year.

a The second table, named “tracks”, contain the album track


names and duration.
d  
k Here is the SQL code to create and populate the tables (click
to expand):

albums table 

tracks table 

This script uses the PDO extension to connect to the


database.

If you want to know more about PHP and MySQL, you can
refer to this complete tutorial:

How to use PHP with MySQL 2


Here is the PDO connection snippet ( remember to change
the connection parameters to suit your development
environment):
https://alexwebdevelop.com/php-json-backend/ 50/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

/* The PDO object */


$pdo = NULL;

/* The connection string. */


$dsn = 'mysql:host=localhost;dbname=myschema';

/* 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();

Then, you need to select the music album from the


database.

For this example, suppose that you need to retrieve the


album with ID 1 (the one already present in the table, if you
2
used the above SQL code).

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

Then, you can add them to the $data array.

Here is how to do it:

/* The album ID to get from the database. */


$albumId = 1;

/* Run the search query. */


$albumQuery = 'SELECT * FROM albums WHERE album_id = :a
$albumParams = array('album_id' => $albumId);

a try
{

d
$albumRes = $pdo->prepare($albumQuery);
$albumRes->execute($albumParams);
}

k catch (PDOException $e)


{
die();
}

$albumRow = $albumRes->fetch(PDO::FETCH_ASSOC);

/* Save the information to the $data array. */


if (is_array($albumRow))
{
$data['Title'] = $albumRow['album_name'];
$data['Artist'] = $albumRow['album_artist'];
$data['Year'] = intval($albumRow['album_year'], 10);
}

Next, you need to select the album tracks.

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

You also need to calculate the album duration to set the


“Duration” variable. To do that, you can sum all the track
lengths.

Here is the code:

/* Initialize the "Duration" element at 0. */


$data['Duration'] = 0;

/* Create the "Tracks" numeric array. */

a
$data['Tracks'] = array();

/* Run the search query.

d */
Note: the result is ordered by track number.

k $tracksQuery = 'SELECT * FROM tracks WHERE track_album


$tracksParams = array('album_id' => $albumId);

try
{
$tracksRes = $pdo->prepare($tracksQuery);
$tracksRes->execute($tracksParams);
}
catch (PDOException $e)
{
die();
}

while (is_array($tracksRow = $tracksRes->fetch(PDO::FET


{
/* Add each track name to the "Tracks" numeric array
$data['Tracks'][] = $tracksRow['track_name'];

/* Add this track's length to the total album length


$data['Duration'] += intval($tracksRow['track_length
}

2
 

Finally, set the JSON content-type, create the JSON object


and return it:

https://alexwebdevelop.com/php-json-backend/ 53/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

/* Create the JSON string. */


$json = json_encode($data, JSON_PRETTY_PRINT);

/* Set the JSON content-type. */


header('Content-Type: application/json');

/* Return the JSON string. */


echo $json;

a Example

d
Send a JSON le as an email attachment

k
In this last example, you will:

Save a JSON le on the local le system


Send the JSON le as an email attachment

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

"Artist": "Jethro Tull",


"Year": 1971,
"Duration": 2599,
"Tracks": [
"Aqualung",
"Cross-Eyed Mary",
"Cheap Day Return",
"Mother Goose",
"Wond'ring Aloud",
"Up to Me",
"My God",
"Hymn 43",
"Slipstream",

a "Locomotive Breath",
"Wind-Up"

d }
]

k
';

The rst thing you need to do is to save the JSON string as a


.json le.

To do that, you need to:

1. De ne the le system path where to save the le.

2. De ne the le name.

3. Save the JSON string into the le.

De ne the le path

If the JSON le should not be accessible to remote users, like


in this case, you must save it outside of the webserver root.
2
“Outside the webserver root” means that you cannot access
it with a remote HTTP request.

However, local PHP scripts will still be able to access it.

https://alexwebdevelop.com/php-json-backend/ 55/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

For example, if the webserver root is “/var/www/public/”, you


can save the le inside “/var/www/private/“.

Let’s de ne a $path variable with the le path:

/* The path where to save the JSON file. */


$path = '/var/www/private/';

 
a
d De ne the le name and save the le

Next, you need to choose a le name. For example:


k music.json.

So, save the le name in the $ leName variable:

/* The JSON file name .*/


$fileName = 'music.json';

Now it’s time to save the JSON string to the le.

The simples way to do that is by using the


le_put_contents() function.

This is how it’s done:

/* Save the file. */


if (file_put_contents($path . $fileName, $json) === FA
2
{
/* Error saving the file. */
echo 'Error saving JSON file.';
die();
}
https://alexwebdevelop.com/php-json-backend/ 56/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

/* Save OK. */
echo 'JSON file successfully saved.';

Send the email

To send emails with PHP, I highly suggest you use


PHPMailer.
a PHPMailer supports a lot of functionalities like attachments,
d HTML emails, SMTP settings and more. And it’s easy to use.

k You can nd all you need to get started in my PHPMailer


complete tutorial.

So, let’s create an email:

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

/* Create the PHPMailer object. */


$email = new PHPMailer(TRUE);

/* Set the mail sender. */


$mail->setFrom('me@mydomain.com');

/* Add the recipient. */


$mail->addAddress('you@yourdomain.com');

/* Set the subject. */


$mail->Subject = 'Hey, here is the music JSON file.';

/* Set the mail message body. */


$mail->Body = 'Hi there. Please find attached the JSON 2

https://alexwebdevelop.com/php-json-backend/ 57/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Now, attach the JSON le:

/* Add the JSON file as attachment. */


$mail->addAttachment($path . $fileName);

And nally, send the email:

a /* Open the try/catch block. */

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.

What is your experience with JSON?


2
Are you going to use what you learned today, or do you
need to use JSON objects in some other way?

Let me know by leaving a comment below.

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 Facebook d Twitter k LinkedIn

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

Alex on June 25, 2020 at 7:24 am

Thank you Scribe, I’m glad this tutorial has been helpful
to you!

Reply

Marcel on June 23, 2020 at 3:09 pm

I love your tutorial sir, what a great article!, am looking up to


others like(.htaccess con guration, what to know from core php
before using frameworks).

Reply

Alex on June 25, 2020 at 7:23 am 2


Thank you, Marcel.

Reply

https://alexwebdevelop.com/php-json-backend/ 59/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Pentabay Software Development on June 16, 2020 at 8:10 am

Well explained Alex. Keep doing more.

Reply

Alex on June 16, 2020 at 8:27 am

Thank you.

Reply

a Anonymous on June 11, 2020 at 12:00 am


d You create an array: $data = array();

k and then you populate it: $data[‘Title’] =


$albumRow[‘album_name’];

If you just start populating without rst creating the array:


$data[‘Title’] = $albumRow[‘album_name’];
it also works.

So, why do you create the array rst?

Reply

Alex on June 11, 2020 at 7:10 am

It is just to make the code more readable.

Reply

uzor ohuegbe on June 9, 2020 at 3:35 pm

Nice article, very informative. Keep up the good job


2
Reply

Alex on June 10, 2020 at 8:33 am

https://alexwebdevelop.com/php-json-backend/ 60/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop

Thanks Uzor

Reply

Selena Johnson on June 9, 2020 at 10:56 am

This is so useful. Thanks

Reply

a Alex on June 9, 2020 at 12:09 pm

Thank you, Selena


d Reply
k
Jan on June 8, 2020 at 12:10 pm

Thanks a lot, I needed a tutorial about JSON just now.

Just a question: shouldn’t the line “if (! le_put_contents($path .


$ leName, $json) === FALSE)” be without the NOT operator?
This way, it will output the error message if the return value of
le_put_contents is everything but FALSE (failure).

Reply

Alex on June 8, 2020 at 12:15 pm

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

Where i can see the older version of this article?

Reply
https://alexwebdevelop.com/php-json-backend/ 61/62
7/1/2020 PHP JSON complete tutorial (with examples) - Alex Web Develop
py

Alex on May 31, 2020 at 6:01 pm

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.

k Privacy policy - Cookie policy

https://alexwebdevelop.com/php-json-backend/ 62/62

You might also like