php中采集抓取页面函数详解
在php中提供了大量的获取远程服务器文件的函数,包括有:file()函数、file_get_contents()函数、fopen()->fread()->fclose()模式、curl方式、fsockopen()函数、socket模式等等,下面我来分别来介绍介绍.
1.file()函数
file() 函数把整个文件读入一个数组中,与 file_get_contents() 类似,不同的是 file() 将文件作为一个数组返回,数组中的每个单元都是文件中相应的一行,包括换行符在内.
如果失败,则返回 false,代码如下:
<?php
$url='http://www.phprm.com';
$lines_array=file($url);
$lines_string=implode('',$lines_array);
echo htmlspecialchars($lines_string);2.file_get_contents()函数
file_get_contents() 函数把整个文件读入一个字符串中.
和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串,file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法,如果操作系统支持,还会使用内存映射技术来增强性能,代码如下:
<?php $url='http://www.phprm.com'; $lines_string=file_get_contents($url); echo htmlspecialchars($lines_string);
使用file_get_contents和fopen必须空间开启allow_url_fopen,方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件.
3.fopen()->fread()->fclose()模式,代码如下:
<
?php
$url='http://www.phprm.com';
$handle=fopen($url,"rb");
$lines_string="";
do{
$data=fread($handle,1024);
if(strlen($data)==0) {
break;
}
$lines_string.=$data;
}while(true);
fclose($handle);
echo htmlspecialchars($lines_string);4.curl方式
使用curl必须空间开启curl,方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:WINDOWSsystem32下;Linux下要安装curl扩展,代码如下:
$url='http://www.phprm.com'; $ch=curl_init(); $timeout=5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $lines_string=curl_exec($ch); curl_close($ch); echo htmlspecialchars($lines_string);
5. fsockopen()函数 socket模式
socket模式能否正确执行,也跟服务器的设置有关系,具体可以通过phpinfo查看服务器开启了哪些通信协议,比如我的本地php socket没开启http,只能使用udp测试一下了.
还有一个以curl_开头的函数,可以实现很多功能,有时间要好好研究,下面是关于fscokopen的介绍.
1.PHP fsockopen函数说明:
Open Internet or Unix domain socket connection(打开套接字链接)
Initiates a socket connection to the resource specified by target .
fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets() , fgetss() , fwrite() , fclose() , and feof() ).就是返回一个文件句柄
开启PHP fsockopen这个函数
PHP fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启,代码如下:
<?php
set_time_limit(0);
$fp = fsockopen("www.phprm.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "POST / HTTP/1.1r\n";
$out .= "Host:www.phprm.comr\n";
$out .= "Connection: Closernr\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}教程网址:http://www.phprm.com/develop/fs5273.html
欢迎收藏∩_∩但请保留本文链接。