PHP - get_meta_tags() 函式



PHP URL get_meta_tags() 函式用於從給定的 URL 中提取所有 meta 標籤的內容屬性,並返回一個數組。此函式可以開啟檔名並逐行解析檔案中的 <meta> 標籤。解析在 </head> 處停止。

name 屬性的值成為鍵,content 屬性的值成為返回陣列的值,因此我們可以輕鬆地使用標準陣列函式來遍歷它或訪問單個值。name 屬性值中的特殊字元將被替換為“_”,其餘部分將轉換為小寫。如果兩個 meta 標籤具有相同的名稱,則只返回最後一個。

語法

以下是 PHP URL get_meta_tags() 函式的語法:

array get_meta_tags ( string $filename [, bool $use_include_path = false ] )

引數

以下是 get_meta_tags() 函式的引數:

  • $filename - 需要從中提取 meta 標籤的 URL 或檔案路徑。

  • $use_include_path - 布林值。如果設定為 true,則函式還會在 include 路徑中搜索該檔案。

返回值

此函式返回包含所有已解析 meta 標籤的陣列。如果沒有 meta 標籤或發生錯誤,它將返回一個空陣列。

PHP 版本

get_meta_tags() 函式在 PHP 4 中引入,並在 PHP 5、PHP 7 和 PHP 8 中繼續執行。

示例 1

這是 PHP URL get_meta_tags() 函式的基本示例,用於從給定的 URL 獲取有關 meta 標籤內容的資訊。

<?php
   // Define url here
   $url = 'http://www.tutorix.com';
   $meta_tags = get_meta_tags($url);
   
   print_r($meta_tags);
?>

輸出

以上程式碼將產生類似於以下的結果:

Array
(
    [viewport] => initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width
    [description] => Affordable Premium Learning - CBSE and State Boards, the amazing learning app which brings you simply easy learning at your mobile and tabs. The best online learning app for 6th - 12th Classes, NEET and IIT/JEE Exams
)

示例 2

此 PHP 示例將向您展示如何使用 get_meta_tags() 函式從本地 HTML 檔案獲取 meta 標籤內容。

<?php
   // Define file path here
   $filename = '/PHP/PhpProjects/myhtml.htm';
   $meta_tags = get_meta_tags($filename);
   
   print_r($meta_tags);
?> 

輸出

這將生成以下輸出:

Array
(
    [viewport] => width=device-width, initial-scale=1.0
)

示例 3

以下程式碼嘗試在使用 get_meta_tags() 函式時未找到 meta 標籤的情況下處理沒有 meta 標籤的情況。

<?php
   /$url = 'http://www.example.com';
   $meta_tags = get_meta_tags($url);
   
   if (empty($meta_tags)) {
       echo 'No meta tags found.';
   } else {
       print_r($meta_tags);
   }
?> 

輸出

這將建立以下輸出:

Array
(
    [viewport] => width=device-width, initial-scale=1.0
)

總結

get_meta_tags() 函式是 PHP 中用於獲取 meta 標籤中存在的內容的內建方法。我們已經看到了不同的示例,以瞭解如何使用此函式從不同的來源獲取 meta 資訊。

php_function_reference.htm
廣告