基本抓取與擷取
<?php
$url = 'https://www.baidu.com';
$html = file_get_contents($url);
// 編碼轉換 (目標站為 GBK)
$html = iconv('GBK', 'UTF-8//IGNORE', $html);
// 擷取 內容
$start = strpos($html, '');
$end = strpos($html, '');
if ($start !== false && $end !== false) {
$title = substr($html, $start + 7, $end - $start - 7);
echo "標題: $title";
}
// 字串替換範例
$html = str_replace(['百度一下', '{hello}'], ['自訂標題', 'jb51.net!'], $html);
echo $html;
?>
進階:cURL 抓取 (支援 Header、Cookie、Timeout、User-Agent)
function fetchUrl(string $url, int $timeout = 10): string|false
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_SSL_VERIFYPEER => false, // 僅測試用,生產請驗證
CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
]);
$content = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
return $errno ? false : $content;
}
$html = fetchUrl('https://www.example.com');
if ($html) {
// 後續解析...
}
建議使用 DOMDocument 解析而非正則
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('' . $html); // 強制 UTF-8
libxml_clear_errors();
$title = $dom->getElementsByTagName('title')->item(0)?->textContent ?? '';
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
$links[] = [
'text' => $a->textContent,
'href' => $a->getAttribute('href')
];
}
法律與道德提醒
- 遵守
robots.txt 爬蟲協定
- 控制請求頻率 (sleep/usleep),避免對目標站造成壓力
- 僅供個人學習研究,勿大量抓取或再散布受版權保護內容
- 商業用途請取得授權或使用官方 API