模擬百度/Google 蜘蛛 UA 抓取目標頁面,解析關鍵 SEO 元素:<title>、<meta keywords>、<meta description>、<body> 內容,快速診斷頁面 SEO 狀態。
<?php
header("Content-Type: text/html; charset=utf-8");
function fetchPage($url) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Baiduspider/2.0; +https://www.baidu.com/search/spider.html)',
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: zh-CN,zh;q=0.9',
],
CURLOPT_SSL_VERIFYPEER => false,
]);
$content = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || !$content) return false;
return $content;
}
function analyzeSEO($html) {
$dom = new DOMDocument();
@$dom->loadHTML('' . $html); // 修正編碼
$xpath = new DOMXPath($dom);
// Title
$titleNode = $xpath->query('//title')->item(0);
$title = $titleNode ? trim($titleNode->textContent) : '無標題';
// Meta Keywords & Description
$keywords = $description = '';
$metas = $xpath->query('//meta');
foreach ($metas as $meta) {
$name = strtolower($meta->getAttribute('name'));
$property = strtolower($meta->getAttribute('property'));
$content = $meta->getAttribute('content');
if ($name === 'keywords' || $property === 'keywords') {
$keywords = $content;
}
if ($name === 'description' || $property === 'og:description') {
$description = $content;
}
}
// Body 文字內容 (去除 script/style)
$bodyNode = $xpath->query('//body')->item(0);
$bodyText = '';
if ($bodyNode) {
// 移除 script/style
$scripts = $xpath->query('.//script | .//style', $bodyNode);
foreach ($scripts as $s) $s->parentNode->removeChild($s);
$bodyText = trim(preg_replace('/\s+/', ' ', $bodyNode->textContent));
$bodyText = mb_substr($bodyText, 0, 500); // 限制長度
}
return compact('title', 'keywords', 'description', 'bodyText');
}
// 主程式
$url = $_POST['url'] ?? 'https://example.com';
$html = fetchPage($url);
if ($html) {
$seo = analyzeSEO($html);
echo "<h3>SEO 分析結果</h3>";
echo "<p><strong>Title:</strong> " . htmlspecialchars($seo['title']) . "</p>";
echo "<p><strong>Keywords:</strong> " . htmlspecialchars($seo['keywords']) . "</p>";
echo "<p><strong>Description:</strong> " . htmlspecialchars($seo['description']) . "</p>";
echo "<p><strong>Body (前500字):</strong> " . htmlspecialchars($seo['bodyText']) . "</p>";
} else {
echo "<p style='color:red'>抓取失敗,請檢查 URL 或網路</p>";
}
| 原始碼問題 | 改良方案 |
|---|---|
| 正則解析 HTML (脆弱) | DOMDocument + XPath (標準、健壯) |
| User-Agent 固定舊版 IE | 可切換 Baiduspider/Googlebot/Chrome UA |
| 無 HTTPS 支援 | cURL 自動處理 SSL |
| 編碼硬編碼 GBK | UTF-8 為主,自動偵測 |
| 無錯誤處理 | HTTP 狀態碼檢查、超時控制 |
| 直接輸出未轉義 | htmlspecialchars 防 XSS |
php seo_check.php https://example.com