How To Get JSON Data in PHP (curl method)

By | June 14, 2016

There are various ways to get JSON data, but the most effective and easiest way is by using PHP curl. JSON as we all know is a text based format to exchange computer data. Most of the companies have their API’s in the JSON format, it can be used for writing simple software applictions, web apps or even mobile apps. To write webservices we need to parse JSON data and present it appropriately so that it can be of use for app users.

In this tutorial our major focus is Getting JSON data using PHP. We will be using cURL since it is very powerful library to transfer data via different protocols like HTTP, FTP. We can easily make requests using GET, POST, PUT. In this tutorial we will use GET method for extracting the JSON data.

Do check PHP Login Script

What we will be doing in this tutorial is that we will be making the HTTP GET request to the Wunderground API. It will get all the JSON data from the URL and it will echo the JSON data. Now the information we will get can be used in various forms like we can show Weather stats about particular region. So here is the code to get JSON data.

Get JSON Data using PHP cURL

$url = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
echo $data;

This way we can make HTTP request using cURL and get JSON data using PHP. After running this script you will see the following result.

get json data

Also check How to Send Mail using Gmail SMTP using PHP

Then you can further convert it to array by using json_decode($data,true). Once you are done with this you can loop through it and get the required values. This way you can get json data using PHP. I hope this method was easy you can try it out with different URL’s so that so you understand the difference. Also check How to convert JSON to array in PHP.