網頁採集(爬蟲)本質是「HTTP 請求 + 內容提取 + 數據存儲」的自動化流程。核心三步驟:
實際項目中,常需多層級採集:先抓列表頁提取詳情頁 URL,再逐個抓取詳情頁解析具體字段。
<?php
$url = 'https://example.com/games/list.html';
$html = @file_get_contents($url);
if ($html === false) die("獲取失敗");
// 提取 SWF 遊戲鏈接:var url = "gameswf/xxx.swf";
preg_match_all('/var url = "gameswf\/(.*?)\.swf";/is', $html, $matches);
$swfFiles = $matches[1]; // 數組:['game1', 'game2', ...]
// 入庫示例(建議用 PDO 預處理防注入)
$pdo = new PDO("mysql:host=localhost;dbname=cms;charset=utf8", "user", "pass");
$stmt = $pdo->prepare("INSERT INTO games (name, swf_path) VALUES (?, ?)");
foreach ($swfFiles as $name) {
$stmt->execute([$name, "gameswf/$name.swf"]);
}
echo "入庫完成,共 " . count($swfFiles) . " 條";
?>
<?php
// 簡單版:copy() 直接複製(需 allow_url_fopen=On)
$remote = 'https://cdn.example.com/images/logo.png';
$local = '/var/www/html/uploads/logo.png';
if (@copy($remote, $local)) {
echo "下載成功";
} else {
echo "下載失敗";
}
// 進階版:支持大文件、斷點續傳、偽造 Referer
function downloadFile($url, $savePath, $referer = '') {
$ch = curl_init($url);
$fp = fopen($savePath, 'wb');
curl_setopt_array($ch, [
CURLOPT_FILE => $fp,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 20,
CURLOPT_REFERER => $referer,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Collector)',
CURLOPT_SSL_VERIFYPEER => false, // 僅測試環境
]);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
return $result && $httpCode === 200;
}
?>
<?php
/**
* 下載圖片並保存
* @param string $url 圖片完整 URL
* @param string $saveName 不含副檔名的保存文件名(路徑+基礎名)
* @return string|false 成功返回完整文件名,失敗返回 false
*/
function saveImage($url, $saveName) {
if (empty($url)) return false;
// 1. 校驗副檔名
$ext = strtolower(strrchr($url, '.'));
if (!in_array($ext, ['.gif', '.jpg', '.jpeg', '.png', '.webp'])) {
return false; // 非圖片鏈接
}
// 2. 獲取二進制內容
$imgData = @file_get_contents($url);
if ($imgData === false || strlen($imgData) < 100) { // 過濾 1x1 像素佔位圖
return false;
}
// 3. 寫入文件
$fullName = $saveName . $ext;
$dir = dirname($fullName);
if (!is_dir($dir)) mkdir($dir, 0755, true);
if (file_put_contents($fullName, $imgData) !== false) {
return $fullName;
}
return false;
}
?>