HTTP Requests Using Curl and Decoding JSON Responses in PHP

You can do http requests using the Curl library and decode the JSON result with json_decode() function. PHP 5.2 and above comes with the JSON library functions.

The following example will send a request to brightcove’s api using curl and extract some video thumbnail image links. The result will be a list of links in json data format.

The json_decode() function will then convert the json object into an associative array and will finally print out the links.


<?php
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");

$url = 'http://api.brightcove.com/services/library?command=find_all_videos'.
'&video_fields=thumbnailURL&token=0Z2dtxTdJAxtbZ-d0U7Bhio2V1Rhr5Iafl5FFtDPY8E.';

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);

$arr = json_decode($r,true);

foreach($arr['items'] as $val)
{
	echo $val['thumbnailURL'].'<br>';
}

Leave a comment

1 Comments.

  1. Zeeshan Arshad

    Phew!! I’ve been trying some solutions and digging into this with Curl, none of them worked.

    This worked very well!

    Thanks bro, (every post worth for someone, nothing wastes :)