up
down
Close
架站盒子
Web Development Box
 

PHP 抓網頁標題、關鍵字、描述

│ 1509 Views │ PHP

語法

<?php
// 要抓取的網頁
$url = "https://kumo.tw/article.php?id=9";

// 讀取網頁源始碼
$getFile = file_get_contents($url);

// 抓取 Title
preg_match("/<title?>(.*)<\/title?>/s", $getFile, $match);
$title = $match[1];

// 抓取 Description 和 Keywords
$getMeta = get_meta_tags($url);
$description = $getMeta["description"];
$keywords = $getMeta["keywords"];

// 印出結果
echo "網址: $url<br>";
echo "標題: $title<br>";
echo "描述: $description<br>";
echo "關鍵字: $keywords<br>";
?>

說明

  1. file_get_contents():函數,將整份文件存進一個字符串中。
  2. preg_match(a, b, $matches[1]);:意思是在b中找到第一個a。
  3. $matches[1]:表示第一個捕獲匹配到的字串,0代表全部。
  4. get_meta_tags:從文件中提取所有meta標籤中的content屬性。

延伸閱讀

本文是否對您有幫助?