load() Function for PHP - Fetch URL Content

来源:互联网 发布:linux怎么启动jenkins 编辑:程序博客网 时间:2024/04/29 03:34

I recently had to develop a small script that willfetch an XML file from the web. All I had to do is download a given URLand read its contents. To my great surprise I found that download thefile using my jx Ajax library was much easier than doing it with PHP.

PHP make this very easy by including functions likefile_get_contents() that has URL support. This code will get you thecontents of an URL.

$contents = file_get_contents('http://example.com/rss.xml');

Unfortunately, this is a huge security threat - and many servershave disabled this feature in PHP. Also this is not the most optimizedmethod to fetch an URL. Also, it is impossible to submit data using thePOST 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. Thesecond 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 youneed to do more complex stuff, just use the second argument to passmore options...

 

The output will be like this...

 

Code


原创粉丝点击