JSON PHP Example

PHP is a most popular language for building web applications. It is a server-side scripting language that enables developers to perform CRUD operations on the database. Support for JSON is present in PHP from version 5.2. PHP has two functions to handle JSON-

  • json_encode()- It converts associative array into JSON data.
  • json_decode()- It converts JSON string into associative array.

Example of json_encode() in PHP

Let's see how you can use json_encode() with the help of an example-

   $arr = array("name" => "Moto G5 Plus",
		"price" => 17000,
 		"color" => array("lunar gray", "fine gold"),
 		"inStock" => true);
   echo json_encode($arr);


{"name":"Moto G5 Plus","price":17000,"color":["lunar gray","fine gold"],"inStock":true}

Now, you will see how to generate JSON from the data obtained from the database

   $conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
   $sql = "select name, price from products limit 0, 10";
   $rows = $conn->query($sql);
   $arr = array("data" => "");
   $arr["data"] = $rows->fetchAll();
   echo json_encode($arr); 	


"data":[{"name":"Moto G5 Plus","price":17000},{"name":"Samsung Galaxy J7","price":15500}]

Example of json_decode() in PHP

You can obtain an array from JSON data using json_decode() function.

   $jsonData = '{"name":"Moto G5 Plus","price":17000,"color":["lunar gray","fine gold"],"inStock":true}';
   $arr = json_decode($jsonData, true); //true is passed to obtain associative array


Array([name]=>Moto G5 Plus [price]=>17000 [color]=>Array([0]=>lunar gray[1]=>fine gold) [inStock]=>1)