load() Function for PHP - Fetch URL Content

本文介绍了一种使用PHP从Web获取XML文件的有效方法。通过自定义的load函数,不仅支持GET和POST请求,还提供了HTTP基本认证等功能,并且能够智能选择cURL或fsockopen进行数据抓取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值