Categories
alexwebdevelop.com

PHP JSON complete tutorial (with examples)

[et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#367FA3″ custom_padding=”9px||20px||false|false”][et_pb_row _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”864px” module_alignment=”center” custom_margin=”|auto||auto|false|false” custom_padding=”16px|32px|16px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.7″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”Montserrat||||||||” header_text_color=”#ffffff” header_font_size=”34px” header_line_height=”1.7em” header_line_height_tablet=”1.4em” header_line_height_phone=”” header_line_height_last_edited=”on|tablet”]

PHP JSON COMPLETE TUTORIAL
THE DEFINITIVE JSON GUIDE FOR PHP DEVELOPERS

[/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”1_2,1_2″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”864px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”1_2″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font_size=”19px” ul_line_height=”2em”]

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.

[/et_pb_text][/et_pb_column][et_pb_column type=”1_2″ _builder_version=”3.26.6″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/04/php-json.png” alt=”JSON with PHP” title_text=”JSON with PHP” align=”center” _builder_version=”4.4.7″ width=”90%” width_tablet=”80%” width_phone=”80%” width_last_edited=”on|phone”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_class=”underline_links” _builder_version=”4.4.2″ background_color=”#ffffff” custom_padding=”24px||||false|false”][et_pb_row _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”832px” custom_padding=”|32px||32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_text _builder_version=”4.4.2″ text_font=”Montserrat||||||||” text_text_color=”#222222″ text_font_size=”15px” link_font=”||||||||” link_font_size=”14px” ul_font=”||||||||” ul_font_size=”16px” ul_line_height=”1.7em” ol_font=”||||||||” ol_font_size=”15px” ol_line_height=”1.8em” header_font=”||||||||” header_3_font=”Montserrat||||||||” header_3_text_align=”center”]

CONTENTS

[/et_pb_text][/et_pb_column][/et_pb_row][et_pb_row _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”832px” custom_padding=”0|32px|0|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_divider _builder_version=”3.21.1″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”1_3,1_3,1_3″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”832px” module_alignment=”center” custom_padding=”0|32px|0|32px|false|true”][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 1″ url=”#json” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/js-small-e.png” alt=”JSON” image_max_width=”80%” image_max_width_tablet=”” image_max_width_phone=”” image_max_width_last_edited=”on|phone” _builder_version=”4.4.2″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

What is JSON?

[/et_pb_blurb][/et_pb_column][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 2″ url=”#json-encoding” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-encode-small-b.png” alt=”JSON encoding” image_max_width=”80%” _builder_version=”4.4.2″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-encoding” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

JSON encoding

[/et_pb_blurb][/et_pb_column][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 3″ url=”#json-encoding-options” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-encoding-options-small-b.png” alt=”JSON encoding options” image_max_width=”80%” _builder_version=”4.4.2″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-encoding-options” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

Encoding options

[/et_pb_blurb][/et_pb_column][/et_pb_row][et_pb_row column_structure=”1_3,1_3,1_3″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”832px” module_alignment=”center” custom_margin=”32px||||false|false” custom_padding=”0|32px|0|32px|false|true”][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 4″ url=”#send-json” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/send-json-small.png” alt=”Send JSON with PHP” image_max_width=”80%” _builder_version=”4.4.7″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#send-json” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

Sending a JSON object

[/et_pb_blurb][/et_pb_column][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 5″ url=”#json-decoding” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-decode-small-b.png” alt=”JSON decoding” image_max_width=”80%” image_max_width_tablet=”” image_max_width_phone=”” image_max_width_last_edited=”on|phone” _builder_version=”4.4.6″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-decoding” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

JSON decoding

[/et_pb_blurb][/et_pb_column][et_pb_column type=”1_3″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”CHAPTER 6″ url=”#json-validation-and-errors” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-validation-small.png” alt=”JSON validation and errors” image_max_width=”80%” _builder_version=”4.4.6″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-validation-and-errors” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

Validation and errors

[/et_pb_blurb][/et_pb_column][/et_pb_row][et_pb_row column_structure=”1_2,1_2″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”832px” module_alignment=”center” custom_margin=”32px||||false|false” custom_padding=”0|32px|0|32px|false|true”][et_pb_column type=”1_2″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”EXAMPLE” url=”#json-from-database” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-db-search-small.png” alt=”JSON from database data” image_max_width=”80%” image_max_width_tablet=”” image_max_width_phone=”” image_max_width_last_edited=”on|phone” _builder_version=”4.4.7″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-from-database” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

Create a JSON object from database data

[/et_pb_blurb][/et_pb_column][et_pb_column type=”1_2″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”EXAMPLE” url=”#json-email” image=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-email-small.png” alt=”JSON email attachment” image_max_width=”80%” _builder_version=”4.4.7″ header_font=”Montserrat||||||||” header_text_align=”center” header_text_color=”#000000″ header_font_size=”14px” header_line_height=”1.5em” body_font=”Montserrat||||||||” body_font_size=”17px” text_orientation=”center” animation=”off” link_option_url=”#json-email” custom_css_main_element=”||” custom_css_blurb_image=”margin-bottom: 15px;”]

Send a JSON file as an email attachment

[/et_pb_blurb][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json” _builder_version=”4.4.2″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_font=”Montserrat||||||||” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

Chapter 1
What is JSON?

[/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font_size=”19px” ul_line_height=”2em”]

You have heard of JSON before.

But what is it, exactly?

And what is it used for?

In this first chapter, I’m going to explain how JSON works and what are its uses in web development.

[/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/js-e.png” alt=”What is JSON” title_text=”What is JSON” align=”center” _builder_version=”4.4.7″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.7″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

What is JSON?

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

As Wikipedia defines it, JSON is a “data interchange format”.

Many web applications use this data format to exchange data over the Internet.

This is how a JSON object looks like:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


{
  "Name": "Alex",
  "Age": 37,
  "Admin": true,
  "Contact": {
    "Site": "alexwebdevelop.com",
    "Phone": 123456789,
    "Address": null	
  },
  "Tags": [
    "php",
    "web",
    "dev"
  ]
}

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat|700|||||||” header_3_text_color=”#444444″ header_3_line_height=”2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

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 identified by the keys.

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

  • Strings, like “Alex” (the Name variable).
  • Numbers, like 37 (the Age variable). Numbers can be integers or floats.
  • 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 value can also be a JSON object itself, containing more nested key => values.

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.

[/et_pb_text][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-nested-objects.png” alt=”JSON nested objects” title_text=”JSON nested objects” align=”center” _builder_version=”4.4.2″ max_width=”90%”][/et_pb_image][et_pb_text _builder_version=”4.4.5″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat|700|||||||” header_3_text_color=”#444444″ header_3_line_height=”2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

There is one more possible type: JSON arrays.

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 not inside an object.

For example, this is a valid JSON:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

How can you use JSON?

JSON is very popular among web developers. Indeed, most of today’s web applications use JSON to send and receive data.

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

[/et_pb_text][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/fontend-json-backend-b.png” alt=”JSON data exchange” title_text=”JSON data exchange” align=”center” _builder_version=”4.4.2″ max_width=”80%” module_alignment=”center”][/et_pb_image][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

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 the more complex XML format:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


<?xml version="1.0" encoding="UTF-8"?>
<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>
  </Tags>
</Element>

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

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.

The good news is: it’s really easy.

 

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.

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-encoding” _builder_version=”4.4.2″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

Chapter 2
JSON encoding

[/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font_size=”19px” ul_line_height=”2em”]

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.

[/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-encode-c-1.png” alt=”JSON encoding” title_text=”JSON encoding” align=”center” _builder_version=”4.4.2″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

In PHP, JSON objects are string variables.

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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


/* A JSON object as a PHP string. */
$json = 
'
{
  "Name": "Alex",
  "Age": 37,
  "Admin": true
}
';

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

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

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.

For example:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


/* The PHP array. */
$array = array("Product" => "Coffee", "Price" => 1.5);

/* The JSON string created from the array. */
$json = json_encode($array);

echo $json;

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

The $json variable looks like this:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

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.

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

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:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


/* The PHP array. */
$array = array("Product" => "Coffee", "Price" => 1.5);

/* The JSON string created from the array, using the JSON_PRETTY_PRINT option. */
$json = json_encode($array, JSON_PRETTY_PRINT);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

Now, the output is more human-friendly:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

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 JSON object.

If you want to create JSON arrays instead, you need to use PHP numeric arrays.

For example:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


/* 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>';
echo $json;
echo '</pre>';

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

This time, the output is a JSON array (note the square brackets and the fact that there are no keys):

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


[
  "Coffee",
  "Chocolate",
  "Tea"
]

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

You can create nested JSON objects and arrays using PHP multi-dimensional arrays.

For example, this is how you can create the first example:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px” custom_margin=”||32px||false|false”]


$array = array();

$array['Name'] = 'Alex';
$array['Age'] = 37;
$array['Admin'] = TRUE;

$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;
echo '</pre>';

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||||false|false” custom_padding=”16px||16px||false|false”]

 

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.

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-encoding-options” _builder_version=”4.4.2″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

Chapter 3
Encoding options

[/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_line_height=”1.8em”]

json_encode() supports 15 different encoding options.

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

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

[/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-encoding-options-b.png” alt=”JSON encoding options” title_text=”JSON encoding options” align=”center” _builder_version=”4.4.2″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

The json_encode() function takes the variable to encode as first 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:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

}

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

has exactly the same value as this:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

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

For example, the “Name 1” and “Name 2” variables in the following JSON are different:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

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:

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

$json = json_encode($array, JSON_PRETTY_PRINT | JSON_FORCE_OBJECT | JSON_THROW_ON_ERROR);

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

All right.

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

 

  • JSON_FORCE_OBJECT

Remember how PHP associative arrays are encoded into 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:

[/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]


/* A PHP numeric array. */
$fruits = array('Apple', 'Banana', 'Coconut');

$json = json_encode($fruits , JSON_PRETTY_PRINT);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

This is the output:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


[
  "Apple",
  "Banana",
  "Coconut"
]

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

But if you use the JSON_FORCE_OBJECT option, the numeric array is encoded as a JSON object like this:

[/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]


/* A PHP numeric array. */
$fruits = array('Apple', 'Banana', 'Coconut');

$json = json_encode($fruits , JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”14px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

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.

 

  • JSON_INVALID_UTF8_SUBSTITUTE
  • 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:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


/* This generates an invalid character. */
$invalidChar = chr(193);

$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3" => $invalidChar);
$json = json_encode($array, JSON_PRETTY_PRINT);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


Warning: json_encode() returned FALSE.

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

If you set the JSON_INVALID_UTF8_SUBSTITUTE option, all invalid characters are replaced by a special “replacement” UTF8 character: “ufffd”.

This way, you can get a valid JSON object even if there are invalid characters somewhere:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


$invalidChar = chr(193);

$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3" => $invalidChar);
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

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:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


$invalidChar = chr(193);

$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3" => $invalidChar);
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_IGNORE);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

JSON_PARTIAL_OUTPUT_ON_ERROR is similar, too.

This option replaces invalid characters with NULL:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


$invalidChar = chr(193);

$array = array("Key 1" => 'A', "Key 2" => 'B', "Key 3" => $invalidChar);
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_PARTIAL_OUTPUT_ON_ERROR);

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

[/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

  • JSON_NUMERIC_CHECK

By default, all PHP strings are encoded as strings in the JSON object.

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:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”14px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

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

If you set the JSON_NUMERIC_CHECK option, integer and float numeric strings become JSON numbers:

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]


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

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

[/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”14px”]


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

[/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

 

  • 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 errors” chapter.

 

There are a few more json_encode() options.

However, they are more specific, and you will probably never use them.

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

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”send-json” _builder_version=”4.4.6″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

Chapter 4
Sending a JSON object

[/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”1.6em”]

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.

In this chapter I’m going to show you exactly how to do that.

    [/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/send-json.png” alt=”Send JSON with PHP” title_text=”Send JSON with PHP” align=”center” _builder_version=”4.4.6″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

    If you are creating a JSON object, it’s because you need to send it to a front-end application or to a remote service.

    You can do that either as a reply to a remote request, or as a direct HTTP request.

       

      Sending a JSON object as a reply to a remote request

      [/et_pb_text][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/send-json-reply.png” alt=”JSON PHP reply” title_text=”JSON PHP reply” align=”center” _builder_version=”4.4.6″ width=”50%” width_tablet=”” width_phone=”80%” width_last_edited=”on|desktop” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|desktop”][/et_pb_image][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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.

       

      When your PHP back-end receives the request, it prepares the response data and encodes it into a JSON object (as you 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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Set the content-type. */
      header('Content-Type: application/json');
      
      /* The array with the data to return. */
      $array = array("Coffee", "Chocolate", "Tea");
      
      /* The JSON string created from the array. */
      $json = json_encode($array);
      
      /* Return the JSON string. */
      echo $json;
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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

      [/et_pb_text][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/remote-service-json.png” alt=”JSON remote service” title_text=”JSON remote service” align=”center” _builder_version=”4.4.2″ max_width=”500px” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|desktop”][/et_pb_image][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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 first 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:

      • when sending data to a cloud service such as an online storage space
      • 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 cURL library.

      First, you need to initialize a cURL session with curl_init(), using the service URL as parameter:

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The remote service URL. */
      $url = 'https://remote-service.com';
      
      /* The cURL session. */
      $curl = curl_init($url);
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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.

      Like this:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      /* 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-Type: application/json')); 
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      Here is an example of how to do that.

      (The YouTube API requires some authentication steps that are not reported here.)

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px” custom_margin=”||32px||false|false”]

      
      /* Create the array with the comment data. */
      $comment = array();
      
      $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?part=snippet&key=12345";
      
      /* The cURL session. */
      $curl = curl_init($url);
      
      /* 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-Type: application/json'));
      
      /* Send the request. */
      $return = curl_exec($curl);
      
      /* Print the API response. */
      echo $return;
      
      

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-decoding” _builder_version=”4.4.6″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

      Chapter 5
      JSON decoding

      [/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”1.6em”]

      You know how to create and send JSON objects from your PHP script.

      In this chapter, you are going to learn how to decode the JSON objects that your PHP application receives.

       

      [/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-decode-b.png” alt=”JSON decoding with PHP” title_text=”JSON decoding with PHP” align=”center” _builder_version=”4.4.7″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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 first 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.

       

      Here is how it works.

      Let’s take our first JSON object example:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = 
      '
      {
        "Name": "Alex",
        "Age": 37,
        "Admin": true,
        "Contact": {
          "Site": "alexwebdevelop.com",
          "Phone": 123456789,
          "Address": null	
        },
        "Tags": [
          "php",
          "web",
          "dev"
        ]
      }
      ';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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
      • JSON strings become PHP strings
      • JSON numbers become PHP integers or floats
      • JSON null values become PHP null values
      • JSON Boolean values become PHP Boolean values (true or false)

      For example (using the above JSON):

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      The output from the above code shows how the PHP object is created:

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]

      
      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]=>
          string(3) "web"
          [2]=>
          string(3) "dev"
        }
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      So, if you want to access the “Age” element of the JSON object, you can do it like this:

      [/et_pb_text][et_pb_text _builder_version=”4.4.5″ text_font=”||||||||” text_font_size=”15px”]

      
      $jsonData = json_decode($json);
      
      echo $jsonData->Age;
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      37
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      $jsonData = json_decode($json);
      
      foreach ($jsonData->Tags as $tag)
      {
        echo $tag . "<br>";
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = 
      '
      {
        "Invalid-php-name": "Variable content"
      }
      ';
      
      $jsonData = json_decode($json);
      
      echo $jsonData->{'Invalid-php-name'};
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      json_decode() options

      The first 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.

       

      Let’s see again the first JSON example.

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The second argument is set to true. */
      $jsonData = json_decode($json, TRUE);
      
      echo '<pre>';
      var_dump($jsonData);
      echo '</pre>';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      The output from the above code shows how the PHP associative array is created:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      array(5) {
        ["Name"]=>
        string(4) "Alex"
        ["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"
        }
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      You can access the elements just like any array element:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      $jsonData = json_decode($json, TRUE);
      
      echo 'Name is: ' . $jsonData['Name'];
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Note that JSON arrays are still decoded into PHP numeric arrays, just like in the previous case.

      Again, you can see from the output that the “Tags” element is a PHP numeric array.

       

      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.

       

      • JSON_THROW_ON_ERROR

      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

      This option works as for json_encode().

      Normally, if the source JSON string contains an invalid character, json_decode() returns NULL.

      For example, if you put an invalid UTF-8 character in the JSON string and you try decoding it, you get NULL in return:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $invalidChar = chr(193);
      
      $json = 
      '
      {
        "Valid char": "a",
        "Invalid char": "' . $invalidChar . '"
      }
      ';
      
      $jsonData = json_decode($json, TRUE);
      
      echo '<pre>';
      var_dump($jsonData);
      echo '</pre>';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      NULL
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      Enabling the JSON_INVALID_UTF8_IGNORE option makes json_decode() ignore invalid characters:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $invalidChar = chr(193);
      
      $json = 
      '
      {
        "Valid char": "a",
        "Invalid char": "' . $invalidChar . '"
      }
      ';
      
      $jsonData = json_decode($json, TRUE, 512, JSON_INVALID_UTF8_IGNORE);
      
      echo '<pre>';
      var_dump($jsonData);
      echo '</pre>';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      • JSON_BIGINT_AS_STRING

      This option is useful when the JSON object contains very large integers.

      When an integer exceeds the maximum PHP size, it is converted into a float and some precision is lost.

      For example:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = 
      '
      {
        "Small number": 10,
        "Big number": 1234567890123456789
      }
      ';
      
      $jsonData = json_decode($json, TRUE);
      
      echo '<pre>';
      var_dump($jsonData);
      echo '</pre>';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      You can see how, in the output array, the big integer is decoded into a float and some precision is lost:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      array(2) {
        ["Small number"]=>
        int(10)
        ["Big number"]=>
        float(1.2345678901235E+18)
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = 
      '
      {
        "Small number": 10,
        "Big number": 1234567890123456789
      }
      ';
      
      $jsonData = json_decode($json, TRUE, 512, JSON_BIGINT_AS_STRING);
      
      echo '<pre>';
      var_dump($jsonData);
      echo '</pre>';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px” custom_margin=”||16px||false|false”]

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

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-validation-and-errors” _builder_version=”4.4.6″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

      Chapter 6
      Validation and errors

      [/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”1.6em”]

      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.

       

      [/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-validation.png” alt=”JSON validation” title_text=”JSON validation” align=”center” _builder_version=”4.4.6″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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 first things I teach in my PHP Security course).

       

      JSON objects are no exception.

      A JSON string received from a remote source is not safe until you validate it.

      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.

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

      Like this:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      /* An invalid JSON string. */
      $json = 
      '
      {
        "Invalid element (no value)"
      }
      ';
      
      $jsonData = json_decode($json);
      
      if (is_null($jsonData))
      {
        echo 'Error decoding JSON.';
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.2″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = '{ }';
      
      $jsonData = json_decode($json, TRUE);
      
      if (!$jsonData)
      {
        echo 'Error decoding JSON.';
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      /* An invalid JSON string. */
      $json = 
      '
      {
       "Invalid element (no value)"
      }
      ';
      
      try
      {
       $jsonData = json_decode($json, FALSE, 512, JSON_THROW_ON_ERROR);
      }
      catch (JsonException $je)
      {
       echo 'Error decoding JSON.<br>';
       echo 'Error number: ' . $je->getCode() . '<br>';
       echo 'Error message: ' . $je->getMessage();
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      JSON variables validation

      After you have successfully decoded the JSON object, you need to validate each variable contained in it.

      As an example, suppose that you expect a JSON object with two variables: a “Name” string variable and a “Price” float variable. Like this:

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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 float number. It must be a positive number lower than a maximum value.

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

      Let’s start from the “Name” variable:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* 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();
        die();
      }
      
      
      /* Check that the "Name" variable is set. */
      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 > $maxLength))
      {
        echo 'Error: "Name" is too short or too long.';
        die();
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      (Of course, the exact validation steps depend on how your application is going to use the variable).

       

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

      [/et_pb_text][et_pb_text _builder_version=”4.4.6″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Check that the "Price" variable is set. */
      if (!isset($jsonArray['Price']))
      {
        echo 'Error: "Price" not set.';
        die();
      }
      
      /* Check that Price is a float. */
      if (!is_numeric($jsonArray['Price']))
      {
        echo 'Error: "Price" is not a number.';
        die();
      }
      
      /* Check that Price is positive and less that a maximum value. */
      $maxPrice = 1000;
      
      if (($jsonArray['Price'] <= 0) || ($jsonArray['Price'] > $maxPrice))
      {
        echo 'Error: Price value is not valid.';
        die();
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      Note:

      If you want to know more about float numbers validation, I explain how to properly validate float variables in this free lesson from my PHP Security course.

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-from-database” _builder_version=”4.4.6″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

      Example
      Create a JSON object from database data

      [/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”1.6em”]

      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.

       

      [/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-db-search.png” alt=”PHP JSON database data” title_text=”PHP JSON database data” align=”center” _builder_version=”4.4.6″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.2″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      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 final JSON looks like:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      {
        "Title": "Aqualung",
        "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",
          "Locomotive Breath",
          "Wind-Up"
        ]
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      The information is stored in two database tables.

      The first table, named “albums”, contain the album name, artist, and year.

      The second table, named “tracks”, contain the album track names and duration.

       

      Here is the SQL code to create and populate the tables (click to expand):

      [/et_pb_text][et_pb_toggle title=”albums table” _builder_version=”4.4.7″ body_font_size=”15px”]

      
      CREATE TABLE `albums` (
        `album_id` int(10) UNSIGNED NOT NULL,
        `album_name` varchar(255) NOT NULL,
        `album_artist` varchar(255) NOT NULL,
        `album_year` smallint(5) UNSIGNED NOT NULL
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      
      INSERT INTO `albums` (`album_id`, `album_name`, `album_artist`, `album_year`) VALUES
      (1, 'Aqualung', 'Jethro Tull', 1971);
      
      ALTER TABLE `albums`
        ADD PRIMARY KEY (`album_id`);
      
      ALTER TABLE `albums`
        MODIFY `album_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
      
      

      [/et_pb_toggle][et_pb_toggle title=”tracks table” _builder_version=”4.4.7″ body_font_size=”15px”]

      
      CREATE TABLE `tracks` (
        `track_id` int(10) UNSIGNED NOT NULL,
        `track_album` int(10) UNSIGNED NOT NULL,
        `track_n` tinyint(3) UNSIGNED NOT NULL,
        `track_name` varchar(255) NOT NULL,
        `track_length` smallint(5) UNSIGNED NOT NULL
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      
      INSERT INTO `tracks` (`track_id`, `track_album`, `track_n`, `track_name`, `track_length`) VALUES
      (1, 1, 1, 'Aqualung', 394),
      (2, 1, 2, 'Cross-Eyed Mary', 246),
      (3, 1, 3, 'Cheap Day Return', 81),
      (4, 1, 4, 'Mother Goose', 231),
      (5, 1, 5, 'Wond'ring Aloud', 113),
      (6, 1, 6, 'Up to Me', 195),
      (7, 1, 7, 'My God', 428),
      (8, 1, 8, 'Hymn 43', 194),
      (9, 1, 9, 'Slipstream', 93),
      (10, 1, 10, 'Locomotive Breath', 263),
      (11, 1, 11, 'Wind-Up', 361);
      
      ALTER TABLE `tracks`
        ADD PRIMARY KEY (`track_id`);
      
      ALTER TABLE `tracks`
        MODIFY `track_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
      
      

      [/et_pb_toggle][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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:

      Here is the PDO connection snippet (remember to change the connection parameters to suit your development environment):

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* 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_EXCEPTION);
      }
      catch (PDOException $e)
      {
        die();
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Now, you need to create the PHP associative array that will be encoded into the JSON object:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The PHP array with the data for the JSON object. */
      $data = array();
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      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 used the above SQL code).

      Once you have the query result, you can get the album title, artist, and year.

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

      Here is how to do it:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The album ID to get from the database. */
      $albumId = 1;
      
      /* Run the search query. */
      $albumQuery = 'SELECT * FROM albums WHERE album_id = :album_id';
      $albumParams = array('album_id' => $albumId);
      
      try
      {
        $albumRes = $pdo->prepare($albumQuery);
        $albumRes->execute($albumParams);
      }
      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);
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Next, you need to select the album tracks.

      You will need to add all the track names to the “Tracks” JSON array.

      Note: since “Tracks” is a JSON array, you need to use a PHP numeric array.

      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:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Initialize the "Duration" element at 0. */
      $data['Duration'] = 0;
      
      /* Create the "Tracks" numeric array. */
      $data['Tracks'] = array();
      
      /*  Run the search query.
          Note: the result is ordered by track number.
      */
      $tracksQuery = 'SELECT * FROM tracks WHERE track_album = :album_id ORDER BY track_n ASC';
      $tracksParams = array('album_id' => $albumId);
      
      try
      {
        $tracksRes = $pdo->prepare($tracksQuery);
        $tracksRes->execute($tracksParams);
      }
      catch (PDOException $e)
      {
        die();
      }
      
      while (is_array($tracksRow = $tracksRes->fetch(PDO::FETCH_ASSOC)))
      {
        /* 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'], 10);
      }
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Finally, set the JSON content-type, create the JSON object and return it:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px” custom_margin=”||16px||false|false” custom_padding=”||||false|false”]

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

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ module_id=”json-email” _builder_version=”4.4.7″ background_color=”#2637A3″ custom_padding=”16px||16px||false|false”][et_pb_row _builder_version=”4.4.2″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”|auto||auto|false|false” custom_padding=”8px|32px|8px|32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”3.27.4″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_text_color=”#ffffff” header_2_line_height=”1.7em”]

      Example
      Send a JSON file as an email attachment

      [/et_pb_text][et_pb_divider _builder_version=”3.26.6″][/et_pb_divider][/et_pb_column][/et_pb_row][et_pb_row column_structure=”3_5,2_5″ _builder_version=”4.4.7″ width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”1px|auto||auto||” custom_padding=”6px|32px||32px|false|true”][et_pb_column type=”3_5″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”1.6em”]

      In this last example, you will:

      • Save a JSON file on the local file system
      • Send the JSON file as an email attachment

       

      [/et_pb_text][/et_pb_column][et_pb_column type=”2_5″ _builder_version=”3.27.3″][et_pb_image src=”https://alexwebdevelop.com/wp-content/uploads/2020/05/json-email.png” alt=”JSON email attachment” title_text=”JSON email attachment” align=”center” _builder_version=”4.4.7″ width=”128px” width_tablet=”128px” width_phone=”” width_last_edited=”on|phone” max_width_tablet=”” max_width_phone=”” max_width_last_edited=”on|phone” module_alignment=”center”][/et_pb_image][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”4.4.2″ background_color=”#eeeeee” custom_margin=”0px||0px||false|false” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|tablet” custom_padding=”0px||0px||false|false”][et_pb_row custom_padding_last_edited=”on|phone” _builder_version=”4.4.7″ background_color=”#ffffff” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” module_alignment=”center” custom_margin=”0px|1668px|0px|418px|false|false” custom_padding=”|32px||32px|false|true” custom_padding_tablet=”” custom_padding_phone=””][et_pb_column type=”4_4″ _builder_version=”3.27.3″][et_pb_text _builder_version=”4.4.6″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      Let’s start with the JSON string from the previous example:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      $json = 
      '
      {
        "Title": "Aqualung",
        "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",
          "Locomotive Breath",
          "Wind-Up"
        ]
      }
      ';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

      The first thing you need to do is to save the JSON string as a .json file.

      To do that, you need to:

      1. Define the file system path where to save the file.
      2. Define the file name.
      3. Save the JSON string into the file.

       

      Define the file path

      If the JSON file should not be accessible to remote users, like in this case, you must save it outside of the webserver root.

      “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.

      For example, if the webserver root is “/var/www/public/”, you can save the file inside “/var/www/private/“.

      Let’s define a $path variable with the file path:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The path where to save the JSON file. */
      $path = '/var/www/private/';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Define the file name and save the file

      Next, you need to choose a file name. For example: music.json.

      So, save the file name in the $fileName variable:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* The JSON file name .*/
      $fileName = 'music.json';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

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

      The simples way to do that is by using the file_put_contents() function.

      This is how it’s done:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Save the file. */
      if (file_put_contents($path . $fileName, $json) === FALSE)
      {
        /* Error saving the file. */
        echo 'Error saving JSON file.';
        die();
      }
      
      /* Save OK. */
      echo 'JSON file successfully saved.';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” header_3_font=”Montserrat||||||||” header_3_text_color=”#222222″ header_3_line_height=”2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Send the email

      To send emails with PHP, I highly suggest you use PHPMailer.

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

      You can find all you need to get started in my PHPMailer complete tutorial.

      So, let’s create an email:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      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 file with the music album data.';
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      Now, attach the JSON file:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Add the JSON file as attachment. */
      $mail->addAttachment($path . $fileName);
      
      

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#000000″ text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” custom_margin=”||0px|” custom_padding=”16px||16px||false|false”]

       

      And finally, send the email:

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”||||||||” text_font_size=”15px”]

      
      /* Open the try/catch block. */
      try
      {
        /* Send the mail. */
        $mail->send();
      }
      catch (Exception $e)
      {
        /* PHPMailer exception. */
        echo $e->errorMessage();
        die();
      }
      
      

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section][et_pb_section fb_built=”1″ _builder_version=”3.27.4″ background_color=”#dddddd” custom_margin=”0px||0px||false|false” custom_padding=”0px||0px||false|false”][et_pb_row _builder_version=”4.4.7″ background_color=”#5577ea” width_tablet=”” width_phone=”100%” width_last_edited=”on|phone” max_width=”800px” custom_margin=”0px|auto|0px|auto|false|false” custom_padding=”|32px||32px|false|true”][et_pb_column type=”4_4″ _builder_version=”3.26.6″][et_pb_text _builder_version=”4.4.7″ text_font=”Montserrat||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.8em” ul_line_height=”1.8em” header_font=”|300|||||||” header_text_color=”#ffffff” header_line_height=”1.7em” header_2_font=”Montserrat||||||||” header_2_text_color=”#ffffff” header_2_line_height=”1.7em” custom_margin=”||0px||false|false” custom_padding=”||0px||false|false”]

      Conclusion

      [/et_pb_text][et_pb_blurb use_icon=”on” font_icon=”%%45%%” icon_color=”#7cda24″ use_icon_font_size=”on” icon_font_size=”48px” _builder_version=”4.4.7″ custom_margin=”0px||0px||false|false” custom_padding=”0px||0px||false|false” animation=”off”][/et_pb_blurb][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_font_size=”19px” text_line_height=”1.6em” link_font=”Nunito||||||||” link_font_size=”19px” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” background_layout=”dark” custom_margin=”||0px|” custom_padding=”||||false|true”]

      In this tutorial, you learned everything you need to use JSON objects with PHP.

      What is your experience with JSON?

      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.

       

      [/et_pb_text][et_pb_text _builder_version=”4.4.7″ text_font=”Nunito||||||||” text_text_color=”#ffffff” text_line_height=”1.6em” link_font=”Nunito||||on||||” link_text_color=”#ffffff” link_line_height=”1.3em” ul_font=”Nunito||||||||” ul_font_size=”19px” ul_line_height=”2.2em” ol_font=”Nunito||||||||” ol_font_size=”19px” ol_line_height=”2.2em” background_layout=”dark” custom_margin=”||0px|” custom_padding=”||||false|true”]

      Copyright notice

      The images used in this post have been downloaded from Freepik.

      [/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]

      Categories
      kinsta.com

      Recommended WordPress Multisite Plugins (Network Management, Migrations, and Backups)

      Performing backups and migrations with basic WordPress sites are pretty straightforward nowadays. There are thousands of step-by-step tutorials on the web and plugins which automate the entire process, making it quick and painless.

      However, when it comes to a WordPress multisite setup, tasks such as backups and migrations are a little more complex.

      This is primarily due to the fact that multisite setups share the same WordPress database and installation. Therefore, unless you’re migrating or backing up the entire multisite, you have to segment the job down to the subsite level.

      Or worse, maybe you’re wanting to turn a subsite back into a normal WordPress install.

      Today we’ll share with you a few WordPress multisite plugins we recommend.

      Ready? Let’s dive in!

      The Challenges of Backing up and Migrating a WordPress Multisite Network

      Backing up and migrating a multisite network is complicated by a few factors:

      • If you want to make separate backups of individual subsites, you won’t be able to use the same methods as for backing up a standalone site.
      • You can migrate subsites into and out of a multisite network, but it isn’t as straightforward as migrating standalone sites.
      • You also might find that you want to duplicate sites within your network, effectively migrating one site to another subdomain or subdirectory before making changes to it.
      • Backing up individual subsites means setting up and storing backups for every single subsite separately. Most backup plugins don’t do this. You’ll need to use a plugin that specifically has compatibility for WordPress multisite.

      Backing up and migrating the entire network is the same as backing up and migrating a single site: the process is no different. But backing up and migrating subsites within the network is made even more complicated because the way files and data for the subsites are stored isn’t exactly straightforward:

      • Each site has its own set of database tables, but all sites store their users on the wp-users and wp-usermeta tables for the entire network. This is so that a user on the network can be added to another site without a new account having to be set up. But it means exporting users isn’t as easy as the other tables.
      • Sites have their upload files stored separately from each other, in a dedicated directory for each subsite within wp-content/uploads. This makes it easier to migrate files from a subsite or to migrate files into it.
      • Plugins and themes are stored once for the network but activated for individual sites. If you want to migrate or back up plugins you’ll need to identify which ones are used for each individual site.

      So is backing up and migrating subsites into and out of a multisite network impossible? Of course it isn’t! There are a number of premium plugins you can use to do it and some free methods.

      In this article, we’ll show you all of those so you can backup and migrate your subsites yourself.

      Installing and Activating WordPress Multisite Plugins on Your WordPress Network

      Before getting into the detail of using a plugin to backup or migrate subsites run your network, you need to know how plugins work in WordPress multisite.

      Each plugin is only installed once on your network, and only the network administrator can do this.

      To install a plugin, go to Network Admin > Plugins > Add New, and install the plugin exactly as you would if you were managing a normal site.

      Installing a plugin in Multisite

      Installing a plugin in Multisite

      The difference is in how you activate those plugins. Plugins can either be network activated, so they’re active on every single site in the network, or they can be activated for individual sites.

      Only the network admin can network activate a plugin. Site admins can activate individual plugins on their own site, but only if the network admin has given permission for this.

      As a network admin, to edit plugin activation permissions, go to Network Admin > Network Settings. Scroll right down to the bottom of the screen and either check or uncheck the Plugins box next to Enable administration menus.

      Enable plugins for site admins

      Enable plugins for site admins

      If plugins are activated for site admins, they can go to the Plugins screen in their admin and activate any plugins they need. You can only turn this off for all plugins, not for a select few (unlike themes).

      If you want a plugin to be activated for every single site in the network, then you need to activate it from the network admin screens.

      Go to Network Admin > Plugins. Find the plugin you want to activate and click the Network Activate link.

      Network activating a plugin

      Network activating a plugin

      Migration and backup plugins, which generally work at a network level and not a site level, are perfect examples of plugins that need to be activated for the whole network, as their function applies to the network and not to individual sites.

      To network deactivate a plugin, simply click the Network Deactivate link where the Network Activate link was. This is only available if you activated the plugin for the whole network. If the plugin was activated for individual sites, either the network admin or the site admin can deactivate it for each site, from within the site admin screens for that site.

      Juggling multiple sites over a network? 🤹â€â™‚ï¸ These plugins will make your life so much easier 😅Click to Tweet

      Plugins for Managing Your WordPress Multisite Network

      There are some plugins that will help you manage your multisite network and work with it more efficiently. They will sometimes give you information that will make the process of backing up or migrating your subsites easier.

      Note that all of these plugins need to be network activated because they work at a network level.

      Multisite Enhancements

      Multisite Enhancements WordPress plugin

      Multisite Enhancements WordPress plugin

      The Multisite Enhancements plugin gives you more information about your multisite network and more tools to work with. A particularly useful feature is the ability to see which plugins or themes are active on which site in the network.

      This means that if you want to backup or migrate an individual site, you’ll know which plugins and themes are activated on it. It’s also useful for testing – if a plugin causes problems on one site in your network, you know which other sites you need to test.

      Multisite enhancements - plugins screen

      Multisite enhancements – plugins screen

      Multisite Toolbar Additions

      Multisite Toolbar Additions WordPress plugin

      Multisite Toolbar Additions WordPress plugin

      The Multisite Toolbar Additions plugin adds some quick shortcuts to the WordPress toolbar for network admins.

      This can save time if you need to do things like manage plugins and themes and configure settings without going through lots of clicks.

      Extra toolbar items

      Extra toolbar items

      User Switching

      User Switching WordPress plugin

      User Switching WordPress plugin

      The User Switching plugin isn’t just for multisite but it’s particularly useful on multisite networks as they have more user roles. If you manage a network and want to troubleshoot a problem one of your site administrators is experiencing, it lets you access the network as if you were using their login.

      User Switching - interface

      User Switching – interface

      Simply go to the Users screen, hover over a user and click the Switch To link. It can save a lot of time logging in and out again and lets you support your network users better.

      WP Multi Network

      WP Multi Network WordPress plugin

      WP Multi Network WordPress plugin

      If you’ve ever wondered if it’s possible to create a multisite network within a multisite network, the WP Multi Network plugin has your answer.

      When installed and network activated, it adds a My Networks menu to the admin menu and lets you turn any of the sites in your multisite network into a network all of its own, meaning you can have two layers of WordPress multisite.

      It’s especially useful for businesses running a multisite network for departments or child companies, which are then able to create networks of their own.

      Important

      This plugin hasn’t been tested with the latest major releases. We strongly suggest to test it in a staging environment first.

      Multisite Langauge Switcher

      Multisite Language Switcher WordPress plugin

      Multisite Language Switcher WordPress plugin

      If you use WordPress multisite to manage a network of sites in different languages, the Multisite Language Switcher plugin will make it easier.

      It adds multilingual support to your entire network, including subdomains and subdirectories, and allows for translation of all content types including pages, posts, custom post types, and taxonomies.

      Backing up or Migrating a Full WordPress Multisite Network

      Backing up the entire network will be useful if you experience problems that affect the entire WordPress installation and not just an individual site. If you have lots of sites on your network, you don’t want to go through the process of restoring each one individually when restoring the entire network would have been easier.

      If you’re planning on migrating individual sites in your network, it makes sense to back up the entire network first, in case of problems.

      Backing up a WordPress multisite network isn’t all that different from backing up or migrating a normal WordPress installation.

      If you’re with Kinsta, our automated backups will give you the peace of mind of knowing that your entire network is being backed up automatically every day.

      To access your backups in MyKinsta, go to Sites, click on your site, and then click Backups in the menu.

      Backups in MyKinsta.

      Backups in MyKinsta.

      From here, you can access your most recent snapshot backups and restore your site from one of these. You can also run a manual backup, which is a good idea before you start migrating any sites into or out of your network.

      If you prefer backing up your WordPress multisite network to an off-site location, we provide two convenient options.

      1. You can click on the “Download†tab and generate a downloadable ZIP file containing your WordPress database and files.
      2. You can click on the “External†tab and configure automatic weekly or monthly backups to an Amazon S3 or Google Cloud Storage bucket.

      If you aren’t with Kinsta, you’ll need to set up backups using a backup plugin. Follow our guide to WordPress backup plugins to get this working.

      Backing up or Migrating up Multisite Subsites

      Migrating or backing up individual subsites is different from migrating or backing up your entire Multisite network because you’ll only have to work with the data and files that apply to that specific site.

      This means migrating or backing up the following:

      • The database tables relating to that site.
      • The theme and plugins in use on that site, which will be stored with themes and plugins for the whole network.
      • The uploads for that site, which will be stored in their own folder within wp-content/uploads.
      • The user data for that site, which will be stored in the main wp-users and wp-usermeta tables for the network.

      This is a complex process, so if you want to do it with a plugin via the admin screens, you’ll have to pay for a premium plugin.

      However, there are a few ways you can do a migration for free if you’re prepared to use the command line or to follow a longer process.

      3 Methods for Backing up and Migrating Multisite Subsites

      There are three methods you can use to migrate subsites for free. These are:

      1. Migrate the relevant database tables and files manually.
      2. Use a workaround involving the use of free plugins.
      3. Run the migration from the command line with the MU-Migration plugin.

      Note that these methods can’t be used for backups: you’ll have to use a premium plugin for that.

      Need a top-notch, fast, and secure hosting for your multisite network? Kinsta provides blazing fast servers and 24/7 world-class support from WordPress experts. Check out our plans

      Let’s take a look at the first two!

      1. Migrate a Subsite Manually

      To migrate a subsite manually, you’ll need to:

      1. Export the database tables for that subsite only. When you import them to the new site, you’ll need to edit the prefix in the SQL file to reflect the database table’s name in the new location.
      2. Export the upload files, which you’ll find in wp-content/uploads/sites/X, where X is the ID of the subsite.
      3. Export any theme and plugin files used in that subsite.

      You can’t easily migrate user records this way and if you have lots of users on the subsite this method is not recommended.

      2. WordPress Multisite Plugins for Migrating or Backing Up Subsites

      Using a dedicated backup or migration plugin that’s compatible with multisite will speed up the process considerably. Here are the most suitable plugins for doing this.

      WP Migrate DB Pro (and WP Migrate DB Pro Multisite Tools)

      The WP Migrate DB Pro plugin claims to help you ‘push/pull your WordPress site with ease’. If you combine it with the WP Migrate DB Pro Multisite Tools add-on, you can use it to migrate a subsite both into and out of a multisite network.

      It lets you migrate a subsite in (almost) any permutation you might need:

      • Push a subsite (including media) to a single site install.
      • Pull a single site install (including media) into a subsite.
      • Push a single site install (database and media) into a multisite install as a subsite
      • Pull a single site install (database and media) into a multisite install as a subsite
      • Export a subsite’s data as a SQL file ready for importing into a single site install.

      The one thing it can’t do right now is migrating a subsite from one multisite network into another multisite network as a subsite. However, there is a workaround you can use.

      So whether you have a subsite in your network that needs to be transferred to its own install, or you have an external site that you need to pull in as a new subsite, this plugin has your back.

      Duplicator Pro

      The Duplicator Pro plugin is designed to help you duplicate and migrate WordPress sites, but it will also work with subsites of a multisite network.

      There are five steps to using the plugin to migrate a subsite into a single site install:

      1. Use the plugin to create a package on your source machine, just as you would on a standard single site.
      2. Copy the installer/archive to the new location and create your database and user.
      3. Go to the installer.
      4. You will see a dropdown containing all the subsites in the package. Choose one and continue with the install.
      5. The subsite chosen in step 4 will be installed as a new standalone.

      WPvivid Backup Pro

      The premium WPvivid Backup Pro plugin is another that’s compatible with multisite.

      The plugin lets you back up or migrate sites using manual migration, automatic migration, or migration via remote storage. With the premium version, you can back up and migrate subsites in your multisite network.

      Info

      The free version of the WPvivid plugin is incompatible with Kinsta hosting because it runs non-incremental backups.

      ManageWP

      The ManageWP plugin isn’t limited to backups and migrations. It includes a range of tools designed to help you manage your site and keep out up to date.

      The premium version comes with tools to help you quickly migrate a WordPress site, including subsites in a multisite network. Both the free and premium versions include backup tools, but you’ll need the premium version to backup subsites individually.

      When using ManageWP with subsites, you’ll need to be aware of the following caveats, which are detailed in the plugin documentation:

      • When you backup a subsite, the whole multisite network is backed up. But you are only charged for that one subsite.
      • You don’t have to back up your parent website if you want to back up a subsite.
      • If you migrate your backup to an external destination, you’ll be uploading the whole multisite network. But the plugin has three restore options, which include the ability to restore only the selected subsite. Plugins and themes will not be restored as these are at the multisite network level.

      Cleaning Up After Migration

      Once you’ve migrated a subsite into or out of a multisite network, you might need to do some clean-up.

      If you’ve migrated the site out of your network and no longer need it, make sure to delete it from your sites.

      Go to Network Admin > Sites and find the site you’ve migrated. Click the Delete link under the site’s name.

      Deleting a site in a WordPress Multisite Network

      Deleting a site in a WordPress Multisite Network

      If your subsite was using a theme or any plugins that aren’t activated on any other sites in your network, you should also delete those. It’s always wise to remove any software from your WordPress installation that isn’t being used.

      Don’t forget to check the new version of the site is working in the location you’ve migrated it to before you do this! (And you might want to take a backup first, just in case.)

      Cloning Sites Within the Network

      Sometimes instead of migrating a subsite out of a multisite network, you want to migrate it within the network. In other words, you want to make a clone of the site.

      This can help you use one site as a template for another site or redevelop a site using the cloned site and then point any domain names at that once it’s ready.

      When it’s time to back up or migrate your multisite network, there’s no need to stress 😌 These plugins were designed to make your life easier!Click to Tweet

      Summary

      Backing up individual subsites in a WordPress multisite network, or migrating them into or out of multisite, isn’t as straightforward as backing up or migrating a single site installation.

      To back up or migrate the subsites in your network, you can migrate the relevant database tables and files manually, use a workaround that needs three free plugins, or for the quickest method, use a premium plugin that’s compatible with WordPress Multisite.

      Categories
      stackify.com

      From Funeral Director to Customer Success Director How Megan Amos Found Her Dream Career in Tech

      Megan Amos didn’t expect to get involved in tech, but once she jumped in, she found her purpose. As nontraditional as it may seem to some, Megan assumed she would have had a long career in the funeral industry, as a fourth-generation funeral director at her family’s funeral home. Though she was gratified by her ability to support people through difficult times, she struggled with the emotional toll of that line of work and wanted to find her true passion in another field.

      Read More: From Funeral Director to Customer Success Director How Megan Amos Found Her Dream Career in Tech