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

4 Comments.

  1. 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 :)

    • Man i’m under 18 and i can’t buy the ebook i visit your siteFor long time i search for this kind of tioarutl beacause i am like you(i can’t sleep to see my travian account)but i am farmed quicly,I am destroyed plz i want to be happy when i see my acount plz help me you are my idol plz help me

  2. Can I simply just say what a relief to discover somebody that really knows what they’re talking about on the web.

    You certainly realize how to bring an issue to light and make it important.
    A lot more people really need to read this and understand this side of
    your story. I can’t believe you aren’t more popular since you surely
    have the gift.

  3. hi i want to hear about some of your tips, but ..I’m not over 18 so I can not buy anyinthg or pay for anyinthg butmy foreldre permits.it is quite impossible that you can find out 2 or 3 small tips that canhelp me a bit? it would be nice.