Hey Folks,
There are times when you need to fetch data from certain URL. This URL can give you RSS feeds or it can be a JSON data. But while writing a script you may often face challenge to fetch the contents from the URL. Some programmers use file_get_contents() function of PHP to get the data from the URL, but by default the http is not supported in the argument of this function. So to get the contents from a URL you have to make a curl request. The procedure to do the same is as follows.
<?php $url='http://twitter.com/statuses/user_timeline/16387631.json'; //rss link for the twitter timeline print_r(get_data($url)); //dumps the content, you can manipulate as you wish to /* gets the data from a URL */ function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } ?>
This is really important function and can be used in multiple ways. In the above example I am fetching my tweets in the form of JSON. You do not need any authentication to do that and hence you can get the output. But some URLs which need to be authenticated may not return anything but an error. So you have to take care of that. This function is pretty basic example of CURL request.
You can enhance this function and have fun.
Stay Digified !!
Sachin Khosla




[...] How do I access my script from another site ? That should work for you . http://www.digimantra.com/technology…sing-curl-php/ You can pass the query string in the URL as well. Thanks Realin [...]
Terrific, my man! I was working with the Netflix odata API, and they suddenly took away jsonp support so my callback wouldn’t fire. With your script, I simple fetched the json, appended my function name wrapper around it, and all is well again. Thanks for sharing!
Hi Sachin nice article , but i have a problem with cURL in php
I want to fetch data from google geocode service , and it api also supports the https , when i request to the google geocode service it returns me no data through cURL, but whenever i paste the url in the browser address bar i gives me the required xml , what is the solution of this problme.
Thanks
You might be having SOP problems?
http://en.wikipedia.org/wiki/Same_origin_policy
Not with cURL.