首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP get_meta_tags() 函數詳解:提取 HTML Meta 標籤內容的實用工具

     編輯:PHP 相關知識

函數定位

get_meta_tags() 解析 HTML 文件(本地或遠程 URL)的 <meta> 標籤,提取 name 和 content 屬性組成關聯陣列。適用於 SEO 分析、內容摘要提取、Open Graph 數據獲取等場景。

語法與參數

array get_meta_tags ( string $filename [, bool $use_include_path = false ] )
  • $filename:HTML 文件路徑或 URL(支援 allow_url_fopen)。
  • $use_include_path:是否在 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
?>

SEO 分析工具:批量提取頁面 Meta

<?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 流式解析器

進階:結合 DOMDocument 完整提取 Meta

<?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(),零依賴、極簡代碼。
  • 需 Open Graph、Twitter Card、微數據用 DOMDocument 或專用庫(Embed\Embed、OpenGraph\OpenGraph)。
  • 遠程抓取設超時上下文:stream_context_create(['http'=>['timeout'=>10]])。
  • 批量分析加併發(cURL 多句柄 / Guzzle 異步)提升效率。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved