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.';

 $curl_options = array(
                    CURLOPT_URL => $url,
                    CURLOPT_HEADER => 0,
                    CURLOPT_RETURNTRANSFER => TRUE,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_SSL_VERIFYPEER => 0,
                    CURLOPT_FOLLOWLOCATION => TRUE,
                    CURLOPT_ENCODING => 'gzip,deflate',
            );

            $ch = curl_init();
            curl_setopt_array( $ch, $curl_options );
            $output = curl_exec( $ch );
            curl_close($ch);

$arr = json_decode($output,true);

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

Leave a comment

5 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

    • How do people do it? No metatr how much we clean, it doesn’t seem to metatr. Two people working full time just doesn’t equate to a magazine worthy home at our residence. I’m glad we’re not the only ones!These photos are stunning!! Your house is absolutely gorgeous! I am totally in love with everything from the tufted furniture, to the gorgeous floral arragements and sweet accessories. Perfection!!

  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.