코드 복사 코드는 다음과 같습니다.
//PHP 단순 html Dom 클래스 라이브러리 파일 포함
include_once('./simplehtmldom/simple_html_dom.php');
//html 수집
function getwebcontent($url){
$ch = cur_init()
$timeout = 10 ;
컬_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); CURLOPT_FOLLOWLOCATION, 1) ;
$contents = Trim(curl_exec($ch));
curl_close($ch)
return $contents;
//제목 및 URL 가져오기
$string =
getwebcontent('http://www.babytree.com/learn/zhunbeihuaiyun/jijibeiyun/2')
//정기 매칭
제목 및 주소 가져오기
preg_match_all( "/< ;li>(.*)/",
$string, $out, PREG_SET_ORDER
foreach( $out as $key => $value){
$article['title'][] = $out[$key][2];
$article['link'][] = "http ://www.babytree.com/learn/article/".$out[$key][1]
}
//URL을 기반으로 기사 콘텐츠 가져오기
foreach( $article['link' ] $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; $ifile_put_contents("{$article[title][$i]}.txt", $article['content'][$i]);
}
/*원래 12시 이전에 보내려고 했는데. . 그런데 보세요, 벌써 3시 30분이에요. . . 어제일지라도
원래는 정규식을 사용하는 것이 기사 내용을 얻는 가장 좋고 빠른 방법입니다
그런데 정규식도 좋지만 정규식은 정말 어렵습니다! 그래서 조금 조사해 보니
인터넷상의 많은 사람들이 PHP Simple Dom을 사용하고 있습니다. 효율성은 조금 느리지만 효과는 여전히 좋습니다
클래스 라이브러리를 포함하는 데 약 7/8이 걸립니다. txt 파일을 작성하는 데 초가 소요됩니다. 특히 기사 콘텐츠를 얻기 위한 일반 규칙은 정말 역겹습니다.
좀 조사해 보세요*/
?>
위의 내용은 PHP simple_html_domphp 일반 컬렉션 기사 코드를 포함하여 PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.