php采集文章
该采集针对文章进行采集的,从第一页采集到最后一页需要提供第一页的地址和了解标题、内容的开始和结束标记进行截取,并且从中找到下一页的地址,再次进行采集 进行采集的函数 caiji()
/*进行采集相关页面函数*/ //header("Content-type: text/html; charset=utf-8"); function get_content_by_socket($url){ $ch = curl_init(); // 2. 设置选项,包括URL curl_setopt($ch, CURLOPT_URL, "$url"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch,CURLOPT_HTTPHEADER,array ("Content-Type: text/xml; charset=utf-8","Expect: 100-continue")); // 3. 执行并获取HTML文档内容 $output = curl_exec($ch); $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($response_code <> '200'){ $i=empty($i)? 0 :($i+1); if($i<50){ get_content_by_socket($url) ; }else{ return $output; } } else { $contents = mb_convert_encoding($output, 'utf-8', 'GBK,UTF-8,ASCII'); //加上这行 解决乱码问题 } //var_dump($output); // 4. 释放curl句柄 curl_close($ch); return $contents; } /*具体操作,采集到的内容处理*/ function caiji($url,$filename){ $c=get_content_by_socket($url); //echo $c; //获取标题 $title=strip_tags(getCont($c,'<div class="titlename">','</div>')); /*没有第字加上---txt有第字默认有目录*/ //$title=stripos($title,'第') ? $title:'第'.$title; //获取下一页链接 $nextpage=getCont($c,'<a class="bdbtn downbtn"','</a>'); //匹配到具体链接 $link=getCont($nextpage,'http','">'); //echo $filename; //echo $link; //获取内容 $content=getCont($c,'<div class="articlecon','</div>'); /*去掉script标签的内容*/ //$content=removeCont($content,'<script','</script>'); /*最后清除所有HTML标签*/ $content=strip_tags($content); //echo $content; /*实现创建文件并读入内容*/ $nfilename = iconv('UTF-8', 'GB2312', $filename);//解决不能名中文名的问题 $myfile = @fopen($nfilename, "a+") or die("Unable to open file!"); //echo filesize($filename);//获取的文件大小都是0 echo $title; //$txt=fread($myfile,filesize($filename)); //$txt=''; /* while (!feof($myfile)) { $txt = fgets($myfile,4096); } $txt.=$title.$content;*/ fwrite($myfile,$title.$content); fclose($myfile); if(!empty($link)){ caiji($link,$filename); }else{ exit(); } } caiji('http://m.chenxitxt.com/xiaoshuo/juanfuchonglai/177246.html','卷夫重来.txt'); /*获取从$front到$last的内容*/ //return preg_replace($pattern,'',strip_tags(substr($nextc,0,$end))); //strip_tags清除HTML标签 函数返回字符串的一部分。 //$str = str_replace(array("_","=","+"),"",$str); function getCont($str,$front,$last){ /*避免前面有重复的字符串,在第一次出现时,截取后面的内容,下次直接处理后面的内容*/ $start=stripos($str,$front);//返回字符串在另一字符串中第一次出现的位置(对大小写不敏感)。 $nextc=substr($str,$start); //echo $nextc."<br>"; $end=stripos($nextc,$last); //echo $end; $res=substr($nextc,0,$end); /*将<br>换成rn*/ $res=str_replace('<br>',' ',$res); /*将 换成空白*/ $res=str_replace(' ',' ',$res); /*清空带有😊类似字符的*/ $res=preg_replace('/&#(d)+;/','',$res); return $res; } /*去掉从$front到$last的内容*/ function removeCont($str,$front,$last){ $start=stripos($str,$front); $nextc=substr($str,$start); $end=stripos($nextc,$last); return $res=substr($nextc,$end); } // Fixes the encoding to uf8