How to extract and access JSON data in PHP
  John Mwaniki /   04 Sep 2021

How to extract and access JSON data in PHP

What is JSON?

JavaScript Object Notation(JSON) is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.

It is easy to generate and parse in many programming languages. It is the most popular and lightweight data-interchange format for web applications and the de-facto format for the data exchange in RESTful web services requests and responses.

In this post, we will cover how to decode a JSON object and access its data in PHP.

Below is an example of a simple JSON object:


{
  "firstName": "John", 
  "lastName": "Doe", 
  "email": "johndoe@gmail.com", 
  "phone": "111-111-1111"
 }

How to receive JSON data in PHP

1. From a POST or GET request

To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents() as below:


$json = file_get_contents("php://input");

For instance, the JSON data is sent below as a POST request:

<?php
$url = "https://www.example.com/register.php" 
$payload = '{
  "firstName": "John", 
  "lastName": "Doe", 
  "email": "johndoe@gmail.com", 
  "phone": "111-111-1111"
 }'; 

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_exec($curl); 
curl_close($curl);

To receive the above request data in the register.php file, just add file_get_contents("php://input") and assign it to a variable for processing eg:

<?php
$mydata = file_get_contents("php://input");

2. Reading a JSON file

A JSON file contains a JSON object and has a file extension of .json. You can also open the file in PHP and access its data.

Similar to POST or GET requests, we use file_get_contents() but instead of having “php://input”, we use the file path.

For example, if we have a JSON file with the path "https://www.example.com/mydata.json", we can access its data as below:

<?php
$mydata = file_get_contents("https://www.example.com/mydata.json");

If the JSON file and the PHP file accessing it are on the same website, we can use a relative path instead of the full file URL.

Extracting/Decoding JSON data in PHP

We use the built-in function json_decode() to convert the JSON string to the appropriate data type such as an object or an array.

Syntax:

<?php
 $data = json_decode($json);

1. Accessing JSON data as a PHP object

By default the json_decode() function returns an object.

Example
The example below decodes a JSON object into a PHP object:

<?php
$json = '{"firstName": "John",  "lastName": "Doe", "email": "johndoe@gmail.com",  "phone": "111-111-1111"}'; 
$data = json_decode($json);
var_dump($data);

The above example outputs below:

object(stdClass)#1 (4) { ["firstName"]=> string(4) "John" ["lastName"]=> string(3) "Doe" ["email"]=> string(17) "johndoe@gmail.com" ["phone"]=> string(12) "111-111-1111" }

To access the PHP object data, you use the object operator (->) after the object name, followed by the key of the key-value pair. This is the same as the name in the name-value pair in JSON object eg $data->firstName .

Example

<?php
$json = '{"firstName": "John",  "lastName": "Doe", "email": "johndoe@gmail.com",  "phone": "111-111-1111"}'; 
$data = json_decode($json);
echo "My name is".$data->firstName." ".$data->lastName;
//Output: My name is John Doe

2. Accessing JSON data as an array

You can as well convert the JSON object to a PHP associative array by passing a second(optional) parameter in the json_decode() function with the boolean value "true" as below. The value is set to false by default if you don't pass it.

<?php
 $data = json_decode($json, true);

The example below decodes JSON object into a PHP associative array:

<?php
$json = '{"firstName": "John",  "lastName": "Doe", "email": "johndoe@gmail.com",  "phone": "111-111-1111"}'; 
$data = json_decode($json, true);
var_dump($data);

The above example outputs below:

array(4) { ["firstName"]=> string(4) "John" ["lastName"]=> string(3) "Doe" ["email"]=> string(17) "johndoe@gmail.com" ["phone"]=> string(12) "111-111-1111" }

You access the data as in any other PHP associative array as in the example below:

<?php
$json = '{"firstName": "John",  "lastName": "Doe", "email": "johndoe@gmail.com",  "phone": "111-111-1111"}'; 
$data = json_decode($json, true);
echo "My name is ".$data["firstName"]." ".$data["lastName"];
//Output: My name is John Doe

3. Accessing data in a nested JSON object

A JSON object may comprise of json objects and arrays as the values in its name-value pairs such as in the example below:


{ 
   "firstName": "John", 
   "lastName": "Doe", 
   "email": "johndoe@gmail.com", 
   "address": { 
         "postalAddress": "12345", 
         "postalCode": "5432", 
         "city": "Nairobi"
      }, 
     "siblings": [ 
          { "name": "Joseph Doe" }, 
          { "name": "Mary Doe" } 
    ] 
}

In the above example, the "address" has an object as its value while "siblings" has an array value comprising of objects.

The easiest way of accessing all the data is decoding the object as an associative array.

Example

<?php
$json = '{ 
   "firstName": "John", 
   "lastName": "Doe", 
   "email": "johndoe@gmail.com", 
   "address": { 
         "postalAddress": "12345", 
         "postalCode": "5432", 
         "city": "Nairobi"
      }, 
     "siblings": [ 
          { "name": "Joseph Doe" }, 
          { "name": "Mary Doe" } 
    ] 
}';
$data = json_decode($json, true);

//Displaying all the data
echo "First Name: ".$data["firstName"]."<br>";
//Output -> First Name: John

echo  "First Name: ".$data["lastName"]."<br>";
//Output -> Last Name: Doe

echo  "Email Address: ".$data["email"]."<br>";
//Output -> Email Address: johndoe@gmail.com

echo  "Postal Address: ".$data["address"]["postalAddress"]."<br>";
//Output -> Postal Address: 12345

echo  "Postal Code: ".$data["address"]["postalCode"]."<br>";
//Output -> Postal Code: 5432

echo  "City: ".$data["address"]["city"]."<br>";
//Output -> City: Nairobi

echo  "Sibling 1: ".$data["siblings"][0]["name"]."<br>";
//Output -> Sibling 1: Joseph Doe

echo  "Sibling 2: ".$data["siblings"][1]["name"]."<br>";
//Output -> Sibling 2: Mary Doe

Looping through an array of objects with foreach()

You may have a large JSON object made of an array of objects, like in the example below:


{
  "countries": [
    {
      "name": "United States of America",
      "code": "US",
      "city": "New York"
    },
    {
      "name": "India",
      "code": "IN",
      "city": "New Delhi"
    },
    {
      "name": "China",
      "code": "CN",
      "city": "Beijing"
    },
    {
      "name": "Germany",
      "code": "DE",
      "city": "Berlin"
    },
    {
      "name": "Kenya",
      "code": "KE",
      "city": "Nairobi"
    }
  ]
}

To access the values of a country in the example above, you just have to know its object position in the array. For example, China is in the third position. But when accessing the array items, we start counting from 0, hence the index of China in the array is 2.

We access the China array object as below:

<?php
//Assign the $json variable the array object in the example above
$data = json_decode($json, true);

//Displaying all the data
echo "Country: ".$data["countries"][2]["name"]."<br>";
//Output -> Country: China

echo  "Code: ".$data["countries"][2]["code"]."<br>";
//Output -> Code: CN

echo  "City: ".$data["countries"][2]["city"]."<br>";
//Output -> City: Beijing

If you want to access all the array data then it can be tiresome and time-consuming to write the code for accessing each at a time especially when the object is large. For such an instance, you can use the foreach() function to loop through all the objects as below:

<?php
$json = '{
  "countries": [
    {
      "name": "United States of America",
      "code": "US",
      "city": "New York"
    },
    {
      "name": "India",
      "code": "IN",
      "city": "New Delhi"
    },
    {
      "name": "China",
      "code": "CN",
      "city": "Beijing"
    },
    {
      "name": "Germany",
      "code": "DE",
      "city": "Berlin"
    },
    {
      "name": "Kenya",
      "code": "KE",
      "city": "Nairobi"
    }
  ]
}';
$countries = json_decode($json)->countries;
foreach($countries as $country){
 echo "Country: ".$country->name."<br>";
 echo  "Code: ".$country->code."<br>";
 echo  "City: ".$country->city."<hr>";
}

Conclusion

In this post, we have covered everything you need to know in extracting and accessing JSON object data using PHP.

You may also want to learn how to form a JSON object in PHP.

If you want to get notified via email when we add more incredible content to our blog, kindly subscribe to our email newsletter.