在無官方 API 的情況下,從目標網站定期抓取新聞標題/列表是常見需求。本文提供一個極簡的 PHP 實現,通過 fopen + 正則匹配提取鏈接文本,適合輕量級監控腳本。
<?php
/**
* 從指定 URL 抓取新聞標題
* @param string $url 目標頁面
* @param int $count 最大抓取條數
* @return array 標題數組
*/
function Get_news($url, $count) {
$handle = @fopen($url, "r");
if (!$handle) {
return []; // 無法打開流
}
$results = [];
$c = 0;
// 正則模式:匹配 標題
// 實際使用時需根據目標站點 HTML 結構調整
$pattern = '/(.*?)<\/a>/i';
while (($line = fgets($handle, 1024)) && $c < $count) {
if (preg_match_all($pattern, $line, $matches, PREG_SET_ORDER)) {
// $matches[0][2] 為第二個捕獲組(標題文本)
$title = strip_tags($matches[0][2]); // 再次去標籤防禦
$results[$c] = $title;
$c++;
}
}
fclose($handle);
return $results;
}
// 使用示例
$url = "https://stu.gdmc.edu.cn/";
$count = 7;
$news = Get_news($url, $count);
foreach ($news as $title) {
// 目標頁面為 GB2312 編碼,轉 UTF-8 輸出
echo iconv("GB2312", "UTF-8//IGNORE", $title) . "
\n";
}
fgets($handle, 1024) 按行讀取,避免大頁面一次性載入內存,適合長列表頁面。
/(.*?)<\/a>/i 針對特定站點結構(大寫 A、雙引號、target="_blank")。老牌中文站常用 GB2312/GBK,iconv("GB2312", "UTF-8//IGNORE", $str) 中 //IGNORE 忽略無法轉換字符,防止中斷。
@fopen 抑制警告,失敗返回空數組,保證腳本繼續執行。
function Get_news_dom($url, $count) {
$html = @file_get_contents($url);
if (!$html) return [];
// 修復編碼聲明
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'GB2312');
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
// 例:查找所有 class="news-link" 的 a 標籤
$nodes = $xpath->query('//a[@class="news-link"]');
$results = [];
foreach ($nodes as $i => $node) {
if ($i >= $count) break;
$results[] = trim($node->textContent);
}
return $results;
}
優勢:結構化查詢、抗 HTML 格式變動、自動處理實體編碼。
User-Agent、Referer、Accept-Language。usleep(mt_rand(500000, 2000000)))。robots.txt 與站點服務條款。本文展示的 fopen + 正則 方案代碼極簡、零依賴,適合一次性腳本或極簡監控;生產環境強烈建議遷移至 DOMDocument/XPath 或專業爬蟲庫,並建立完善的異常監控、編碼處理、反爬應對與合規機制。