查詢

get_meta_tags()函式—用法及示例

「 從指定的檔案中獲取所有的HTML meta標籤內容,並返回一個關聯陣列 」


函式名稱:get_meta_tags()

函式描述:該函式用於從指定的檔案中獲取所有的HTML meta標籤內容,並返回一個關聯陣列。

適用版本:PHP 4, PHP 5, PHP 7

語法:get_meta_tags(string $filename, bool $use_include_path = false) : array|false

引數:

  • $filename:必需,指定要解析的HTML檔案的路徑。
  • $use_include_path:可選,如果設定為true,則在include_path中搜尋檔案。

返回值:

  • 如果成功解析HTML檔案並獲取到meta標籤,則返回一個包含所有meta標籤的關聯陣列。
  • 如果解析失敗或者檔案不存在,則返回false。

示例:

// 示例HTML檔案內容:
// <html>
// <head>
// <meta name="description" content="This is a sample description">
// <meta name="keywords" content="php, programming, web development">
// </head>
// <body>
// ...
// </body>
// </html>

$filename = 'path/to/file.html';
$metaTags = get_meta_tags($filename);

if ($metaTags !== false) {
    echo "Meta tags found:\n";
    foreach ($metaTags as $name => $content) {
        echo "$name: $content\n";
    }
} else {
    echo "Failed to parse meta tags from the file.";
}

輸出:

Meta tags found:
description: This is a sample description
keywords: php, programming, web development

注意事項:

  • 該函式只能解析HTML檔案中的meta標籤,無法解析其他型別的標籤或者XML文件。
  • meta標籤的名稱和內容將作為關聯陣列的鍵值對返回,名稱為meta標籤的name屬性值,內容為meta標籤的content屬性值。
  • 由於該函式需要讀取檔案內容,所以需要確保PHP具有讀取檔案的許可權,並且指定的檔案路徑是正確的。
補充糾錯
上一個函式: get_object_vars()函式
下一個函式: get_mangled_object_vars()函式
熱門PHP函式
分享連結