遠程獲取目標頁面 → 正則提取所需字段 → 入庫或生成靜態頁。核心函數:file_get_contents() (PHP 5+) + preg_match_all()。
目標站:八路中文網 (86zw.com),采集《回到明朝當王爺》為例。
# 規律:https://www.86zw.com/Book/{書號}/Index.aspx
$number = $_POST['number']; // 用戶輸入書號
$url = "https://www.86zw.com/Book/$number/Index.aspx";
$content = file_get_contents($url);
// 書名:<span class="booktitle">《書名》</span>
preg_match_all('/<span class="booktitle">(.*?)<\/span>/is', $content, $title);
// $title[1][0] 為書名
// 作者、分類同理,根據頁面結構編寫正則
# 章節列表規律:https://www.86zw.com/Html/Book/{分類號}/{書號}/List.shtm
// 從書目頁提取分類號
preg_match_all('/Html\/Book\/[0-9]+\/[0-9]+\/List\.shtm/is', $content, $typeid);
// 切取函數
function cut($string, $start, $end) {
$msg = explode($start, $string);
$msg = explode($end, $msg[1]);
return $msg[0];
}
$start = "Html/Book/";
$end = "List.shtm";
$typeid = cut($typeid[0][0], $start, $end);
$typeid = explode("/", $typeid); // $typeid[0] = 分類號
$listUrl = "https://www.86zw.com/Html/Book/{$typeid[0]}/$number/List.shtm";
$listContent = file_get_contents($listUrl);
// 提取章節鏈接
preg_match_all('/<a href="([^"]+)">(.*?)<\/a>/is', $listContent, $chapters);
// $chapters[1] = 章節URL, $chapters[2] = 章節標題
foreach ($chapters[1] as $idx => $chapterUrl) {
$chapterContent = file_get_contents($chapterUrl);
// 正則提取正文內容...
// 入庫:INSERT INTO chapters (book_id, title, content, sort) VALUES ...
// 或生成靜態:file_put_contents("book/$number/$idx.html", $content);
}
// 通用切取函數
function cut($string, $start, $end) {
$msg = explode($start, $string);
if (isset($msg[1])) {
$msg = explode($end, $msg[1]);
return $msg[0];
}
return '';
}
法律提醒:采集前請確認目標站點
robots.txt與服務條款,尊重版權,合規使用數據。