How to Handle JSON data using PHP
Since JSON appeared on the web, all web services are offering JSON as their primary data format for data interchanging. The reason JSON is so popular is because it is lightweight and easy for humans to read and write. Today I want to show you how we can use this JSON data in our projects using PHP. Let's say a health website is offering information about fruits in JSON data to the public, and you want to use them on your web project. Their JSON data looks like this :- 1
- 2
- 3
- 4
- 5
- 6
{
"Apple":"Helps lower the chance of developing diabetes and asthma.",
"Avocado":"Helps lower cholesterol levels when eaten instead of harmful saturated fats.",
"Banana":" 105 calories, 3 g fibre, source of vitamin B6, potassium and folate",
"Blackberry":"Helps reduce the risk of stroke and cancer."
}
PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
//get JSON data using either file_get_contents or cURL
$result = file_get_contents("http://some-health-site.com/path/to/json/");
//decode JSON string & convert it into a PHP variable.
$json_object = json_decode($result);
//simply print-out the variable
echo $json_object->Avocado;
echo $json_object->Banana;