Make HTTP Requests Using Curl and Decoding JSON Responses in PHP

PHP has built-in Curl library that let’s you communicate with other servers. The Curl library is enabled by installing cUrl extension in PHP.INI. You just need to uncomment “extension=php_curl.dll” in PHP.INI file to install Curl library.

If you’re a PHP developer, you certainly need to get data from other server or need to make request to other server like payment gateways integration, fetching catalog etc. By using Curl library, You can make easily make HTTP request to server and get the required data.  You can also decode the JSON result with json_decode() function.

Here in this post, We will make a Curl request to Soundcloud API to get the details of a track. The result will be a list of track details in json data format. The json_decode() function will then convert the JSON object into an array and will finally print out the details.
<?php
$requesturl='http://api.soundcloud.com/tracks/54518918.json?client_id=d70658d99cfe7bf44a398e3f8b1785ed';
$ch=curl_init($requesturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cexecute=curl_exec($ch);
curl_close($ch);
$result = json_decode($cexecute,true);
echo "Id:".$result['id'];
echo "Title:".$result['title'];
echo 'Description:".$result['description'];
?>

5 thoughts on “Make HTTP Requests Using Curl and Decoding JSON Responses in PHP

  1. Hi im creating a script which is very similar to this but i cant get it to work. Im trying to get print out details of train tickets for a given date. so far i’ve got this..

    Any help would be greatly Appreciated

Leave a Reply

Your email address will not be published. Required fields are marked *