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-
Let's see how you can use json_encode() with the help of an example-
<?php $arr = array("name" => "Moto G5 Plus", "price" => 17000, "color" => array("lunar gray", "fine gold"), "inStock" => true); echo json_encode($arr); ?>
Output
{"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
<?php $conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMORE_EXCEPTION); $sql = "select name, price from products limit 0, 10"; $rows = $conn->query($sql); $arr = array("data" => ""); $arr["data"] = $rows->fetchAll(); echo json_encode($arr); ?>
Output
"data":[{"name":"Moto G5 Plus","price":17000},{"name":"Samsung Galaxy J7","price":15500}]
You can obtain an array from JSON data using json_decode() function.
<?php $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 print_r($arr);?>
Output
Array([name]=>Moto G5 Plus [price]=>17000 [color]=>Array([0]=>lunar gray[1]=>fine gold) [inStock]=>1)