PHP读取远程文件的三种方法

WBOY
Release: 2016-06-20 13:02:46
Original
1372 people have browsed it

PHP读取远程文件的几种方法总结及区别分析。

1.file_get_contents

<p><?php</p>$url = 'http://www.xxx.com/';<br />$contents = file_get_contents($url);<br />//如果出现中文乱码使用下面代码<br />//$getcontent = iconv(“gb2312″, “utf-8″,file_get_contents($url));<br />//echo $getcontent;<br />echo $contents;<br />?>
Copy after login

2.curl

<p><?php</p>$url = “http://www.xxx.com/”;<br />$ch = curl_init();<br />$timeout = 5;<br />curl_setopt($ch, CURLOPT_URL, $url);<br />curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br />curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//在需要用户检测的网页里需要增加下面两行<br />//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);<br />//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.”:”.US_PWD);<br />$contents = curl_exec($ch);<br />curl_close($ch);<br />echo $contents;<br /><p>?>
Copy after login

3.fopen->fread->fclose

<p><?php</p>$handle = fopen (“http://www.xxx.com/”, “rb”);<br />$contents = “”;<br />do {<br />$data = fread($handle, 8192);<br />if (strlen($data) == 0)<br />{break;}<br />$contents .= $data;<br />} while(true);<br />fclose ($handle);<br />echo $contents;<br /><p>?>
Copy after login

file_get_contents、fopen、curl区别分析:

1.使用file_get_contents和fopen必须空间开启allow_url_fopen。

方法:编辑php.ini,设 置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。

2.使用curl必须空间开启curl。

方法:WIN下修改php.ini,将extension=php_curl.dll前面的分号去掉, 而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;

Linux下要安装curl扩展。

建议打开URL时使用file_get_contents()方法,可优化打开速度


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template