How to Handle JSON data using PHP

How to Handle JSON data using PHP

JSON is a primary data format for data interchange. It is very lightweight and easy to read and writes. Nowadays every tool in the web used JSON data format for data interchange. It’s fast, easy to use, readable, and lightweight. In this tutorial, I will let you know how you can parse the JSON data in PHP and how you can convert PHP array into a JSON data format.

What is JSON?

JSON stands for JavaScript Object Notation. JSON is a lightweight data format used for transmitting data from a server to a web page.

How to print JSON file data in PHP

sometimes we need to parse JSON file in PHP. In below code snippet you will get to know you how you can print JSON file data in PHP

{
"mango":"very good for health.",
"Banana":" keeps you fit.",
"Avocado":"Helps reduce the risk of stroke."
}

Using PHP we can easily fetch and decode this information :

//get JSON data using either file_get_contents or cURL
$result = file_get_contents("http://websiteName.com/path/to/jsonfile/");

//decode JSON string & convert it into a PHP variable. 
$json_data = json_decode($result);

//simply print-out the variable 
echo $json_data->mango;
echo $json_data->Banana;

Converting a PHP array to JSON

you can simply convert PHP array to JSON data, by using json_encode(). check the below code.

$data = array('name'=>'abc','gender'=>'Male');

Usage:

echo json_encode($data);

Output:

{"name":"abc","gender":"Male"}

How to print JSON data in PHP

You can also convert JSON data in PHP and print the variable.

$data = '{"name":"abc","gender":"Male"}';

Usage:

$output =  json_decode($data);

Output:

print_r($output);

//simply print-out the variable 
echo $output->name;
echo $output->gender;