phpQuery 是 PHP 版 jQuery,支援 CSS 選擇器、DOM 遍歷、操作操作,讓伺服器端採集網頁如同瀏覽器端般直觀。
<?php
require_once 'phpQuery/phpQuery.php'; // 或 composer require electrolinux/phpquery
// 從 URL 載入
phpQuery::newDocumentFile('https://example.com/news');
$title = pq('.headline h1:eq(0)')->html();
echo $title;
// 從字串載入
$html = file_get_contents('https://example.com');
phpQuery::newDocument($html);
$links = pq('a')->attr('href');
| 需求 | phpQuery 代碼 | 說明 |
|---|---|---|
| 取得標題文字 | pq('h1')->text() | 純文字,去除標籤 |
| 取得 HTML 內容 | pq('.content')->html() | 保留內部標籤 |
| 取得屬性 | pq('img')->attr('src') | 單一元素 |
| 遍歷列表 | foreach(pq('.item') as $li) { pq($li)->find('h2')->text(); } | 需包裝 $li 為 pq 物件 |
| 第 N 個元素 | pq('li:eq(2)') | 索引從 0 開始 |
| 父/子/兄弟 | pq($el)->parent() / children() / next() | DOM 遍歷 |
<?php
phpQuery::newDocumentFile('https://blog.example.com');
$articles = [];
foreach (pq('.post-list .post') as $post) {
$pq = pq($post); // 重要:包裝為 phpQuery 物件
$articles[] = [
'title' => $pq->find('h2 a')->text(),
'url' => $pq->find('h2 a')->attr('href'),
'summary' => $pq->find('.excerpt')->text(),
'date' => $pq->find('.meta .date')->attr('datetime'),
];
}
print_r($articles);
<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<contact><name>張三</name><age>22</age></contact>
<contact><name>王五</name><age>18</age></contact>
</root>
XML;
phpQuery::newDocument($xml, 'text/xml'); // 指定 MIME 類型
$age = pq('contact:eq(0) > age')->text(); // 22
echo $age;
phpQuery 內部靜態陣列 phpQuery::$documents 會保存所有解析過的文件,大量採集導致記憶體暴增。
<?php
// 錯誤示範:記憶體持續增長
while ($url = $queue->pop()) {
phpQuery::newDocumentFile($url);
// 處理...
}
// 正確:每次解析後清理
while ($url = $queue->pop()) {
phpQuery::newDocumentFile($url);
// 處理...
phpQuery::$documents = []; // 釋放文件物件
// 或 unset(phpQuery::$documents[$id]);
}
phpQuery::newDocument($html, 'utf-8') 或先 iconv()pq('form')->find('input[name=token]')->val('abc') 修改表單值try { phpQuery::newDocumentFile($url); } catch (Exception $e) { log($e); }| 工具 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| phpQuery | jQuery 語法、功能豐富 | 記憶體洩漏、維護較少 | 中小型採集、熟悉 jQuery |
| DOMDocument + XPath | 內建、記憶體穩定、標準 | 語法較繁瑣 | 大型採集、生產環境 |
| Symfony DomCrawler | 現代、測試友善、無洩漏 | 需 Composer 依賴 | 新專案、整合 Symfony |
| Goutte | 內建 HTTP Client、表單處理 | 依賴 Guzzle | 需登入/互動採集 |