Using cURL (Client URLs) with PHP
From time to time PHP web developers need to grab a webpage from somewhere else on the internet to use its contents for some use.
On a shared server system it’s likely that the use of the fopen() or simplexml_load_file() tags for external data is probably prohibited, and for good reason.
However, don’t fear because using PHP’s inbuilt cURL functions, we have a way to fetch this information. cURL, which stands for Client URLs can look complicated at first glance and can be thought of as another subject to learn but in our instance here all we need it for is to fetch a webpage across the World Wide Web and for that it’s not so bad!
Let’s look at a piece of PHP code to fetch a Yahoo RSS feed.
<?php $xml = simplexml_load_file('http://rss.news.yahoo.com/rss/oddlyenough'); ?>
Now this would normally be fine, but not in our shared server where the simplexml_load_file() function is not permitted. Below is aversion of the code above, using cURL to complete the exact same function and can be used in your web development projects easily.
PHP cURL Code
<?php $ch = curl_init("http://rss.news.yahoo.com/rss/oddlyenough"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $return = curl_exec($ch); curl_close($ch); ?>
We now have the information we wanted before but it is saved in our $return variable above. Let’s try and explain a little of what exactly is happening here:
$ch = curl_init(“http://rss.news.yahoo.com/rss/oddlyenough”);
The curl_init() function initialises our cURL request with the URL of the page we want to fetch.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
The function above tells cURL that we want the data from the webpage returned and not displayed on our browser.
$return = curl_exec($ch);
Placing the curl_exec() function in it’s own variable, executes the cURL command and then places the return results into our variable $return which we can then manipulate as any other variable using PHP.
This is only the beginning of what cURL can do. Using cURL you can login to remote websites and automate tasks as if it was a real person performing the tasks and much, much more.
If you would like any help using cURL or any other scripting languages or would like help with your own web design or development needs then why not get in contact with us here at Network Intellect.