$ch = curl_init(); // 初始化cURL
$url = "http://example.com"; // 目標網址
curl_setopt($ch, CURLOPT_URL, $url); // 設置請求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回內容而不是直接輸出
$response = curl_exec($ch); // 執行請求
curl_close($ch); // 關閉會話
echo $response; // 輸出網頁內容
這段代碼完成了從遠程服務器拉取頁面HTML的基本過程。
$response = "<title>Example Title</title>"; // 假設的HTML內容
$pattern = '/<title>(.*?)<\/title>/'; // 匹配<title>內容
preg_match($pattern, $response, $matches); // 執行匹配
$title = $matches[1]; // 獲取標題
echo $title; // 輸出:Example Title
這種方式適合結構較簡單或對性能要求較高的場景。
$response = "<html><body>
<a href='http://example.com'>Link 1</a>
<a href='http://example.org'>Link 2</a>
</body></html>"; // 網頁HTML內容
$dom = new DOMDocument();
libxml_use_internal_errors(true); // 防止HTML解析報錯
$dom->loadHTML($response); // 載入HTML內容
$links = $dom->getElementsByTagName('a'); // 獲取所有a標籤
foreach ($links as $link) {
echo $link->getAttribute('href') . "<br>"; // 輸出链接地址
}
相比正則匹配,DOMDocument對不規範HTML的容錯性更強,推薦在結構複雜頁面中使用。
新聞聚合與媒體監控
商品價格對比與電商分析
實時天氣與交通信息抓取
金融行情與股票數據採集
通過靈活組合網絡請求與HTML解析技術,PHP開發者可以構建各種自動化數據提取工具。