<?php
$url = 'https://www.php.net';
$lines = file($url); // 逐行讀入數組
$html = implode('', $lines); // 合併為完整字符串
// 正則提取 ... 內容
if (preg_match('/<head>(.*)<\/head>/is', $html, $matches)) {
echo $matches[1]; // $matches[1] 為捕獲組內容
}
?>
關鍵點:
file() 直接支援 HTTP/HTTPS URL(需 allow_url_fopen=On)implode('', $lines) 無縫合併,避免換行符干擾正則s 修飾符使 . 匹配換行,i 忽略大小寫function get_content_by_socket($url, $host) {
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp) return false;
$header = "GET /{$url} HTTP/1.1\r\n";
$header .= "Host: {$host}\r\n";
$header .= "User-Agent: Mozilla/5.0 (compatible; PHP Bot)\r\n";
$header .= "Connection: Close\r\n\r\n";
fwrite($fp, $header);
$response = '';
while (!feof($fp)) { $response .= fgets($fp, 8192); }
fclose($fp);
return $response;
}
以下函數集支援:索引頁批量下載、多媒體鏈接提取、目錄遍歷、去重存儲:
<?php
// 1. 批量下載索引頁
function get_index($save_file, $prefix = "index_") {
$count = 68; $i = 1;
@unlink($save_file);
$fp = fopen($save_file, "a+") or die("Open failed");
while ($i < $count) {
$url = $prefix . $i . ".htm";
$content = get_url($url);
fwrite($fp, get_content_url($url, $content));
$i++;
}
fclose($fp);
}
// 2. 提取頁面內所有鏈接
function get_content_url($host_url, $html) {
$rex = '/href\s*=\s*["\']*([^"\'>\s]+)["\'>\s]*/is';
preg_match_all($rex, $html, $r);
$result = '';
foreach ($r[1] as $link) {
if (preg_match('/^(down.*\.html)$/i', $link)) {
$result .= $host_url . $link . "\n";
}
}
return $result;
}
// 3. 解析多媒體對象(示例:href + 鏈接文本)
function get_content_object($str) {
$rex = '/href\s*=\s*["\']*([^"\'>\s]+)["\'>\s]*(.*?<\/b>)/is';
preg_match_all($rex, $str, $m);
if (count($m) == 3) {
$m[2] = str_replace(['多媒體:', ' '], '', $m[2]);
return $m[1][0] . "|--:**:--|" . $m[2][0] . "\n";
}
return '';
}
// 4. 通用 HTTP 獲取(支援重定向、錯誤處理)
function get_url($url) {
if (!preg_match('/^https?:\/\/[^\/].+$/', $url)) die("Invalid URL");
$fp = fopen($url, "r") or die("Open url failed: $url");
$content = '';
while ($fc = fread($fp, 8192)) $content .= $fc;
fclose($fp);
if (empty($content)) die("Get content failed: $url");
return $content;
}
?>
Content-Type charset,必要時 mb_convert_encoding() 統一轉 UTF-8User-Agent、Referer、Cookie;控制請求頻率;使用代理 IP 池DOMDocument + DOMXPath,比正則更穩健robots.txt、網站服務條款,避免法律風險