发布于 2014-10-18 14:36:20 | 112 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的PHP Simple HTML DOM Parser 中文手册,程序狗速度看过来!

PHP Simple HTML DOM Parser HTML 文档解析器

PHP Simple HTML DOM Parser是一个 PHP5 的 HTML 文档解析器


本文是一个php下的simple_html_dom.php结合正则表达式实现的采集文章功能代码,感兴趣的同学参考下。

 
<?php
//包含PHP Simple html Dom 类库文件
include_once('./simplehtmldom/simple_html_dom.php');

//采集html
function getwebcontent($url){
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
$contents = trim(curl_exec($ch));
curl_close($ch);
return $contents;
}


//获得标题和url
$string =
getwebcontent('http://www.test.com/learn/zhunbeihuaiyun/jijibeiyun/2');
//正则匹配<li>获取标题和地址
preg_match_all ("/<li><a href="/learn/article/(.*)">(.*)</a>/",
$string, $out, PREG_SET_ORDER);

foreach($out as $key => $value){
$article['title'][] = $out[$key][2];
$article['link'][] = "http://www.test.com/learn/article/".$out[$key][1];
}

//根据url获取文章内容
foreach($article['link'] as $key=>$value){
$html = file_get_html($value);
$div = $html->find('div[id=pagenum_0]');
$article[content][] = $div[0]->innertext;
}
//标题转码---真正用的时候不用这步--因为咱本来就要用utf8的
//不转码还真不能保存成文件
foreach($article[title] as $key=>$value){
$article[title][$key] = iconv('utf-8', 'gbk', $value);//转码
}
//存入文件
$num = count($article['title']);
for($i=0; $i<$num; $i++){
file_put_contents("{$article[title][$i]}.txt", $article['content'][$i]);
}

?>


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务