I recently had to develop a small script that will fetch an XML file from the web. All I had to do is download a given URL and read its contents. To my great surprise I found that download the file using my jx Ajax library was much easier than doing it with PHP.
PHP make this very easy by including functions like file_get_contents() that has URL support. This code will get you the contents of an URL.
$contents = file_get_contents('http://example.com/rss.xml');
Unfortunately, this is a huge security threat - and many servers have disabled this feature in PHP. Also this is not the most optimized method to fetch an URL. Also, it is impossible to submit data using the POST method using this function.
Other Options - curl and fsockopen
PHP provide other two method to fetch an URL - Curl and Fsockopen . But to use this I have to write a lot more code.
load()
So I decided to create my own function that makes it much more easier.
Features
- Easy to use.
- Supports Get and Post methods.
- Supports HTTP Basic Authentication - this will work - http://binny:password@example.com/
- Supports both Curl and Fsockopen. Tries to use curl - if it is not available, users fsockopen.
- Secure URL(https) supported with Curl
Options
The first argument of this function is the URL to be fetched. The second argument is an associative array. This is an optional argument. The following values are supported in this array.
-
return_info
-
Possible values - true/false
If this is true, the function will return an associative array rather than just a string. The array will contain 3 elements...
-
headers
- An associative array containing all the headers returned by the server. body
- A string - the contents of the URL. info
- Some information about the fetch. This is the result returned by the 'curl_getinfo()' function. Supported only with Curl.
method
-
Possible Values - post/get
Specifies the method to be used.
modified_since
- If this option is set, the 'If-Modified-Since' header will be used. This will make sure that the URL will be fetched only it was modified.
Examples
The code to fetch the contents of an URL will look like this...
$contents = load('http://example.com/rss.xml');
Simple, no? This will just return the contents of the URL. If you need to do more complex stuff, just use the second argument to pass more options...
The output will be like this...
Code