教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php利用fopen实现简单的网页采集程序

php利用fopen实现简单的网页采集程序

发布时间:2016-12-03   编辑:jiaochengji.com
教程集为您提供php利用fopen实现简单的网页采集程序等资源,欢迎您收藏本站,我们将为您提供最新的php利用fopen实现简单的网页采集程序资源
这个采集程序是一个非常简单的程序了,个人认为不适合于大量数据采集了单页还是没有问题了,因为fopen函数对于远程文件操作与多线程时是非常的不理想的,这个只是一个作者写的觉得好玩合出来了。
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy3840')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy3840>


/**
* 根据URL采集网页内容
*
* @param string $url 链接地址
* @return string
*/

private function fetchbyurl($url){
$handle = fopen($url, ‘r’);
$content = ”;
while (!feof($handle)){
$content .= fgets($handle, 10000);
}
return $content;
//?$this->utf8_iconv($content):”;
}

/*获取所有匹配的内容
* @param string $str 内容
* @param string $start 起始匹配
* @param string $end 中止匹配
* @return array
*/

private function utf8_iconv($content){
return iconv(‘GBK’, ‘UTF-8′, $content);
}
private function strCutAll($str,$start,$end){
$content = explode($start,$str);
$matchs = array();
$sum = count($content);
for( $i = 1;$i < $sum;$i ){
$tmp = explode($end,$content[$i]);
$matchs[] = $tmp[0];
unset($tmp);
}
return $matchs;
}

/*获取第一个匹配的内容
* @param string $str 内容
* @param string $start 起始匹配
* @param string $end 中止匹配
* @return string
*/
private function strCut($str, $start, $end){
$content = strstr( $str, $start );
$content = substr( $content, strlen( $start ), strpos( $content, $end ) - strlen( $start ) );
return $content;
}

测试:

/*采集程序*/header("content-Type: text/html; charset=utf-8"); //$nr = file_get_contents(‘/webback/php/php-yi-ju-hua-hou-men-zhuan’); $nr = $this->fetchbyurl(‘/webback/php/php-yi-ju-hua-hou-men-zhuan’);//推荐,还可以用curl dump($this->strCut($nr,’<div class="context">’,'<div class="betterrelated">’));//得到内容。需要进一步过滤用(preg_match_all) dump($this->strCutAll($nr,’<title>’,'</title>’)); 得到标题

您可能感兴趣的文章:
php利用fopen实现简单的网页采集程序
php采集程序
PHP采集器的简单示例代码
file_get_contents只读取网页的部分内容
phpQuery采集网页内容的示例代码
php采集远程图片的思路与实现代码
PHP采集远程图片的实例代码
分享一个PHP采集远程图片
PHP采集网页图片保存到本地的示例代码
PHP的错误是什么

[关闭]
~ ~