#native_company# #native_desc#
#native_cta#

Processing JSON in PHP

By Octavia Andreea Anghel
on March 20, 2014

Introduction

This article explains how to use the JavaScript Object Notation (JSON) extension in PHP, going step by step through a series of essential operations. First, let’s see what the JSON extension is and what the advantages are of using it. JSON is an object string notation, it is defined as a subset of JavaScript’s syntax and its general-purpose is to interchange data format. As you probably know, JSON was first made to be used with JavaScript for accessing remote data, but now it is used by many other languages because JSON data is platform independent data format. JSON can be used natively in JavaScript, but you can also use it in a server-client application logic. You can learn more about JSON and about the languages that use this extension here.

JSON supports different kind of data types like: numbers, strings, boolean, array data and object. Below is listed a simple format of JSON data which shows the details of a book:

 

{"1":"JSF 2.0 Cookbook","2":"Anghel Leonard","3":"2010","4":"Packt Publishing","5":"45"}

Creating and Parsing a JSON Object in PHP

Starting with PHP 5.2.0 the JSON extension is default. To handle JSON data we have two useful functions used for converting and parsing JSON data trough PHP: json_encode() and json_decode() described below:

string json_encode (

mixed $value [, int $options = 0 [, int $depth = 512 ]] ) – Returns the JSON representation of a value where the $value argument can be any type except a resource („ A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.”). The $options argument is optional and may be one of these bitmasks: JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_HEX_QUOT, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE (learn more about JSON predefined constants). The $depth argument sets the maximum depth and must be greater than zero.

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] ) – Takes a JSON encoded string and converts it into a PHP variable trough the $json argument. The $assoc argument returns objects that will be converted into associative arrays when is set to TRUE; $depth is optional and represents the user specified recursion depth; $options is also optional and represents the bitmask of JSON decode options (currently, only JSON_BIGINT_AS_STRING is supported).

And now, let’s create the JSON data format using a PHP array and the json_encode() method described above:

Listing: EncodeJSON_array.php

<?php
  //the PHP array that will encoded in the JSON format
  $array = array(1 => 'title', 2 => 'author', 3 => 'yearofpublication', 4 => 'publisher', 5 => 'price');
 
  //encoding the PHP array
  echo json_encode($array);
?> 

The above code generates the JSON data listed below:

{"1":"title","2":"author","3":"yearofpublication","4":"publisher","5":"price"}

Now, let’s decode above JSON data in PHP, using the json_decode() method described above:

Listing: DecodeJSON_array.php

<?php
  //the JSON string to be decoded
  $json_string='{"1":"title","2":"author","3":"yearofpublication","4":"publisher","5":"price"}';
 
  //decoding the above JSON string
  $json=json_decode($json_string,true);
 
  //listing the array
  foreach($json as $prop => $value)
   echo '<br/>'. $prop.' : '. $value;
?> 

The output of the Listing DecodeJSON_array.php is:

1 : title
2 : author
3 : yearofpublication
4 : publisher
5 : price

Now, let’s see how to work with objects. The next application encodes an PHP object, in this case $book, and then is decoded as an object, using the json_decode($result)function and as an array, by setting the True argument into the json_decode($result,true):

Listing: EncodeDecodeJSON_object.php

<?php

class Book {
public $title = "";
public $author = "";
public $yearofpublication = "";
}

$book = new Book();
$book->title = "JSF Cookbook";
$book->author = "Anghel Leonard";
$book->yearofpublication="2012";

$result = json_encode($book);
echo 'The JSON representation is:'.$result.'<br>';

echo '************************'.'<br>';
echo 'Decoding the JSON data format into an PHP object:'.'<br>';
$decoded = json_decode($result);

var_dump($decoded);

echo $decoded->title.'<br>';
echo $decoded->author.'<br>';
echo $decoded->yearofpublication.'<br>';

echo '************************'.'<br>';
echo 'Decoding the JSON data format into an PHP array:'.'<br>';
$json = json_decode($result,true);

//listing the array
foreach($json as $prop => $value)
echo '<br/>'. $prop .' : '. $value;
?> 

The output of the EncodeDecodeJSON_object.php listing is:

The JSON representation is:{"title":"JSF Cookbook","author":"Anghel Leonard","yearofpublication":"2012"}
************************
Decoding the JSON data format into an PHP object:
object(stdClass)#2 (3) { ["title"]=> string(12) "JSF Cookbook" ["author"]=> string(14) "Anghel Leonard" ["yearofpublication"]=> string(4) "2012" } JSF Cookbook
Anghel Leonard
2012
************************
Decoding the JSON data format into an PHP array:

title : JSF Cookbook
author : Anghel Leonard
yearofpublication : 2012

Serializing a JSON Object

Starting with PHP 5.4.0, the interface JsonSerializable is available. Using this interface, objects that implements JsonSerializable interface can customize their JSON representation when are encoded with json_encode(). The jsonSerialize function specifies data which should be serialized to JSON and has the below prototype:

abstract public

mixed JsonSerializable::jsonSerialize ( void ) – Serializes the object to a value that can be serialized natively by json_encode(). You may notice that this function has no arguments.

The listing below is a simple implementation of using the JsonSerializable interface.

Listing: UsingJsonSerialzableInterface.php

<?php

class ArrayValue implements JsonSerializable {

  public function __construct(array $array) {

    $this->array = $array;

  }



  public function jsonSerialize() {

    return $this->array;

  }

}



$array = array('title', 'author', 'yearofpublication');

echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);

?> 

The output of UsingJsonSerialzableInterface.php listing is:

title
author
yearofpublication

Extracting Data from a Database into a JSON String

To accomplish this task, I used a Singleton class for database connection because I think that a database connection is exactly the type of task that can be done through a Singleton class: you should have one instance communicate with a database because it helps you maintain only one connection instance instead of multiple ones and because of that is so much faster for your JSON tests. So, the below listing represents a Singleton class for obtaining database connections:

Listing: DatabaseSingletonClass.php

<?php
class DatabaseSingletonClass
{
 
  //set this constants to connect to your database - the default settings are just for testing tasks
  const MYSQL_HOST = "127.0.0.1";
  const MYSQL_USER = "root";
  const MYSQL_PASS = "";
  const MYSQL_DB = "bookstore";
 
  //A static member variable representing the class instance
  private static $_instance = null;
 
  //Have a single globally accessible static method
  public static function getInstance()
  {
    if( !is_object(self::$_instance) ) { //or if( is_null(self::$_instance) ) or if( self::$_instance == null )     
        self::$_instance = new MySQLi(self::MYSQL_HOST, self::MYSQL_USER, self::MYSQL_PASS, self::MYSQL_DB);
            if(self::$_instance->connect_error)
            {
                throw new Exception('MySQL connection failed: ' . self::$_instance->connect_error);
            }
     }
    return self::$_instance;
  }
}
?> 

And now, we can do what we have proposed in this section. To extract data from a database, in our case, bookstore, into JSON strings we need first to query the bookstore database and select all from the books table. Then, using the mysqli_fetch_row() method, each row of data from the result set is returned as an enumerated array, and this is the moment when the rows are encoded to JSON using the json_encode() function, described in a previous section. In the output you will also see the initial rows of data from the books table.

Listing: ExtractDataFromDatabaseUsingJSON.php

<?php
 include_once('DatabaseSingletonClass.php'); 
 
 $result = DatabaseSingletonClass::getInstance()->query("SELECT * FROM books");
 if($result) {
  echo("<table border='1'>");
  while ($row = mysqli_fetch_row($result)) {
    echo("<tr>");
    for($i = 0; $i < count($row); $i++) {
     echo "<td>".$row[$i]."</td>";
     print json_encode($row[$i]);
    }
 
    echo("<br></tr>");
  } 
  echo("</table><br><br>");
 
  $result->close();
 
 } else { echo("An error occurred while processing!"); }
?> 

The output of the ExtractDataFromDatabaseUsingJSON.php listing is:

"1""Annabel Lee""Edgar Allan Poe""1850""The Literature Page""256"
"2""The Ballad of Reading Gaol""Oscar Wilde""1898""The Literature Page""45"
"3""Winnetow""Karl May""1956""The truth""123"
"4""JBoos Tools 3""Anghel Leonard""2009""Packt""569"

How to Store a JSON String into a Database

To store a JSON string into a database, in our case bookstore, we need the JSON string that will be stored, in this case {“title”: “some book”} and we also need an UPDATE statement that will do the job.

Notice that the DatabaseSigletonClass.php class is listed in the above section.

Listing: StoreAJSONStringInDatabase.php

<?php
 include_once('DatabaseSingletonClass.php');  
 $json_string = '{"title": "some book"}';   
 $result = DatabaseSingletonClass::getInstance()->query("UPDATE books SET title = '$json_string' WHERE id = '1'");
?> 

After running StoreAJSONStringInDatabase.php listing you need to check your table from the database. I use Aqua Data Studio program for database administration, so the next figures are printscreens from that program containing the modification:

Notice that first title has been modified, and the Annabel Lee title was replaced by a given {“title”: “some book”} JSON string.

Encrypting/Decrypting a JSON Object in PHP

In this section you will see how to encrypt/decrypt a JSON object in PHP, so to accomplish this task we will use the OpenSSL. OpenSSL is an open-source implementation of the SSL and TLS protocols and is used for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data.

But first, we will show you an example that only encrypts a string using the PHP three built-in encryption functions: md5(), crypt(), and sha1():

Listing: EncryptJSONString1.php

<?php
 
   $json_string = '{"1":"title","2":"author","3":"yearofpublication","4":"publisher","5":"price"}';
 
   //Calculates the md5 hash 
   $md5_data = md5($json_string);
 
   //This function encrypts data
   $crypt = crypt($json_string);
 
   //Calculate the sha1 hash
   $sha1 = sha1($json_string);
 
  echo $md5_data.'<br>';
  echo $crypt.'<br>';
  echo $sha1.'<br>'; 
 
  ?> 

The output of listing EncryptJSONString1.php is:

c024f30d63bb82a2a61548b7bd114fb1
$1$Td5.gm1.$aRzr37pusGNM5anbt2N7N/
6d59f4825a318cc8737a055d92e7cd4cf46215e0

The next example uses OpenSSL for encrypt and decrypt a JSON string in PHP. To encrypt, OpenSSL have the openssl_encrypt function, which have the following prototype:

string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] ) - Encrypts given data, using the $data argument, with given method, $method represents the cipher method, using a password, $password argument, and returns encrypted string on success or FALSE on failure. 

To decrypt, OpenSSL have the openssl_decrypt function, which have the below prototype:

string openssl_decrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] ) - takes an encoded string and decrypts it using a given method and key and returns the decrypted string on success or FALSE on failure. 

Listing: EncryptJSONString2.php

<?php
 
$json_string = '{"1":"title","2":"author","3":"yearofpublication","4":"publisher","5":"price"}';
$pass = 'JSON';
$method = 'aes128';
 
$encrypt = openssl_encrypt ($json_string, $method, $pass);
echo 'The encrypted JSON string is: '.$encrypt.'<br><br>';
 
$decrypt = openssl_decrypt($encrypt,$method,$pass);
echo 'The decrypted JSON string is: '.$decrypt;
 
?> 

The encrypted JSON string is:

NBJmw0HuZnUBGqfcOfLU5NAwR8WZ5vBtSnnl5lswAUxfHWiQ8YHrz7ExzoGHy05OvigU/SBslFl1sgFXaD+O7apwXPSqt27/04JUNgAST3Y="}

The decrypted JSON string is:

{"1":"title","2":"author","3":"yearofpublication","4":"publisher","5":"price"}

The next example encrypts/decrypts a JSON object and lists the results in both cases:

<?php
 
class Book {
  public $title = "";
  public $author = "";
  public $yearofpublication = "";
}
 
$book = new Book();
$book->title = "JSF 2.0 Cookbook";
$book->author = "Anghel Leonard";
$book->yearofpublication="2010";
 
$json_string = json_encode($book);
echo 'The JSON representation is:'.$result.'<br>';
 
$pass = 'JSON';
$method = 'aes128';
 
$encrypt = openssl_encrypt ($json_string, $method, $pass);
echo 'The encrypted JSON string is: '.$encrypt.'<br><br>';
 
$decrypt = openssl_decrypt($encrypt,$method,$pass);
echo 'The decrypted JSON string is: '.$decrypt;
?> 

The output of the above listing is:

The JSON representation is:{"title":"JSF 2.0 Cookbook","author":"Anghel Leonard","yearofpublication":"2010"}
The encrypted JSON string is: n5FXSTqhgW5Zt51Z038TnBbwd13PEMKjFocFB8l7UT1o0+qhD/nPTnrESEKUAB6+EyN8w3a9GhTjosN+djzZp89Q4QzBF1YSLn6wvpunFGpfZSVHGOrHtUtX6JofUecb
The decrypted JSON string is: {"title":"JSF 2.0 Cookbook","author":"Anghel Leonard","yearofpublication":"2010"}

Summary

This article has shown you how to parse and serialize a JSON object, how to extract data from a database as a JSON string, how to store a JSON object into a database and in the last section of this article you have seen how to encrypt and decrypt a JSON object using OpenSSL.