使用 file() 或 file_get_contents() 取得遠端網頁內容,配合正則表達式提取所需資訊(如 <head> 區塊)。本文逐步示範抓取、合併陣列、正則解析全流程。
<?php
$url = 'https://www.php.net';
?>
<?php
$lines = file($url); // 每行一個元素
?>
<?php
$content = implode('', $lines); // 空字串作分隔符直接連接
?>
<?php
// 模式: 到 之間的所有內容 (含換行)
$pattern = '/(.*)<\/head>/is'; // i=忽略大小寫, s=單行模式 (點號匹配換行)
if (preg_match($pattern, $content, $matches)) {
echo $matches[1]; // 第 1 捕獲組即為內容
} else {
echo '未找到 head 區塊';
}
?>
<?php
$url = 'https://www.php.net';
$lines = @file($url); // @ 抑制警告
if ($lines === false) {
die('無法抓取遠端內容');
}
$content = implode('', $lines);
$pattern = '/(.*)<\/head>/is';
if (preg_match($pattern, $content, $matches)) {
echo '<pre>';
echo htmlspecialchars($matches[1]); // 安全輸出
echo '</pre>';
} else {
echo '解析失敗';
}
?>
<?php
function fetchUrl($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
]);
$content = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno) return false;
return $content;
}
$content = fetchUrl('https://www.php.net');
if ($content && preg_match('/(.*)<\/head>/is', $content, $m)) {
echo htmlspecialchars($m[1]);
}
?>
| 修飾符 | 含義 |
|---|---|
i | 忽略大小寫 |
s | 單行模式:. 匹配換行符 |
m | 多行模式:^$ 匹配行首尾 |
U | 非貪婪模式:*? 最少匹配 |
DOMDocument、DOMXPath 或 QueryList 等專用解析器。robots.txt、設定合理 User-Agent、控制請求頻率。mb_convert_encoding($content, 'UTF-8', 'auto')。<?php
$dom = new DOMDocument();
@$dom->loadHTML($content); // @ 抑制 HTML5 標籤警告
$xpath = new DOMXPath($dom);
$head = $xpath->query('//head')->item(0);
if ($head) {
echo $dom->saveHTML($head);
}
?>