get_meta_tags() 解析 HTML 文件(本地或遠程 URL)的 <meta> 標籤,提取 name 和 content 屬性組成關聯陣列。適用於 SEO 分析、內容摘要提取、Open Graph 數據獲取等場景。
array get_meta_tags ( string $filename [, bool $use_include_path = false ] )
allow_url_fopen)。include_path 搜尋(僅本地文件)。<head> 區域,遇 </head> 停止。name 屬性值(小寫、特殊字符轉 _),值為 content 屬性值。name 後者覆蓋前者。property(如 og:title)、http-equiv、charset 等屬性。<?php
// 假設 www.example.com 包含:
//
//
//
//
$tags = get_meta_tags('https://www.example.com/');
echo $tags['author']; // John Doe
echo $tags['keywords']; // php, tutorial
echo $tags['description']; // A PHP manual
echo $tags['geo_position']; // 49.33;-86.59
?>
<?php
function analyze_seo_meta($urls) {
$results = [];
foreach ($urls as $url) {
$tags = @get_meta_tags($url);
if ($tags === false) {
$results[$url] = ['error' => '無法獲取或解析'];
continue;
}
$results[$url] = [
'title' => $tags['title'] ?? '缺失',
'description' => $tags['description'] ?? '缺失',
'keywords' => $tags['keywords'] ?? '缺失',
'author' => $tags['author'] ?? '未知',
'og_title' => $tags['og_title'] ?? '不支援', // get_meta_tags 不解析 property
'og_description' => $tags['og_description'] ?? '不支援',
];
}
return $results;
}
$urls = ['https://example.com', 'https://blog.example.com'];
print_r(analyze_seo_meta($urls));
?>
| 需求 | get_meta_tags | 替代方案 |
|---|---|---|
| 解析 property (og:, twitter:) | ❌ 不支援 | DOMDocument + XPath / Masterminds\HTML5 |
| 解析 http-equiv (Content-Type, refresh) | ❌ 不支援 | DOMDocument |
| 解析 charset | ❌ 不支援 | HTTP Header + DOMDocument |
| 惡意/畸形 HTML 容錯 | 中等(基於流解析) | Masterminds\HTML5 (HTML5 規範解析器) |
| 大文件/流式處理 | ❌ 全量載入 | XMLReader / HTML5 流式解析器 |
<?php
function get_all_meta($html) {
$dom = new DOMDocument();
@$dom->loadHTML($html); // 抑制畸形 HTML 警告
$metas = [];
foreach ($dom->getElementsByTagName('meta') as $meta) {
$name = $meta->getAttribute('name')
?: $meta->getAttribute('property')
?: $meta->getAttribute('http-equiv')
?: $meta->getAttribute('charset');
$content = $meta->getAttribute('content');
if ($name) {
$key = strtolower(str_replace(['-', ':'], '_', $name));
$metas[$key] = $content;
}
}
return $metas;
}
// 使用
$html = file_get_contents('https://example.com');
$meta = get_all_meta($html);
// 包含 og:title, twitter:card, http-equiv 等所有類型
?>
name/content 提取用 get_meta_tags(),零依賴、極簡代碼。DOMDocument 或專用庫(Embed\Embed、OpenGraph\OpenGraph)。stream_context_create(['http'=>['timeout'=>10]])。