在 PHP 中解析 HTML 文檔一直是開發者的痛點。正則表達式脆弱難維護,DOMDocument API 繁瑣。phpQuery 移植了 jQuery 的選擇器語法和鏈式操作風格,讓服務端 HTML 解析變得極其直觀高效。
phpQuery-0.9.5.386-onefile.zip引入單文件版:
<?php
include('phpQuery-onefile.php');
?>
假設有 test.html 包含以下結構:
<div class="thumb" id="Thumb-13164-3640">
<a href="/Spiderman-City-Drive">
<img src="/thumb/12/Spiderman-City-Drive.jpg" alt="">
<span class="GameName" id="GameName-13164-3640">Spiderman City Drive</span>
<span class="GameRating" id="GameRating-13164-3640">
<span></span>
</span>
</a>
</div>
<div class="thumb" id="Thumb-13169-5946">
<a href="/Spiderman-City-Raid">
<img src="/thumb/12/Spiderman-City-Raid.jpg" alt="">
<span class="GameName" id="GameName-13169-5946">Spiderman - City Raid</span>
<span class="GameRating" id="GameRating-13169-5946">
<span></span>
</span>
</a>
</div>
PHP 解析代碼:
<?php
include('phpQuery-onefile.php');
$filePath = 'test.html';
$fileContent = file_get_contents($filePath);
$doc = phpQuery::newDocumentHTML($fileContent);
phpQuery::selectDocument($doc);
$data = array(
'name' => array(),
'href' => array(),
'img' => array()
);
// 提取所有鏈接 href
foreach (pq('a') as $t) {
$href = $t->getAttribute('href');
$data['href'][] = $href;
}
// 提取所有圖片 src
$domain = 'https://www.gahe.com'; // 域名前綴
foreach (pq('img') as $img) {
$data['img'][] = $domain . $img->getAttribute('src');
}
// 提取遊戲名稱(通過 nodeValue 獲取文本內容)
foreach (pq('.GameName') as $name) {
$data['name'][] = $name->nodeValue;
}
var_dump($data);
?>
array (size=3)
'name' =>
array (size=2)
0 => string 'Spiderman City Drive' (length=20)
1 => string 'Spiderman - City Raid' (length=21)
'href' =>
array (size=2)
0 => string 'https://www.gahe.com/Spiderman-City-Drive' (length=40)
1 => string 'https://www.gahe.com/Spiderman-City-Raid' (length=39)
'img' =>
array (size=2)
0 => string 'https://www.gahe.com/thumb/12/Spiderman-City-Drive.jpg' (length=53)
1 => string 'https://www.gahe.com/thumb/12/Spiderman-City-Raid.jpg' (length=52)
pq('div.thumb a')、pq('#id')、pq('.class') 等完整 CSS 選擇器pq('div')->find('a')->attr('href')phpQuery::selectDocument($doc) 管理多文檔上下文| 操作 | 代碼示例 |
|---|---|
| 創建文檔 | phpQuery::newDocumentHTML($html) |
| 從文件加載 | phpQuery::newDocumentFileHTML('test.html') |
| 選擇元素 | pq('.class'), pq('#id'), pq('div > a') |
| 獲取屬性 | $el->getAttribute('href') 或 pq($el)->attr('href') |
| 獲取文本 | $el->nodeValue 或 pq($el)->text() |
| 獲取 HTML | pq($el)->html() 或 pq($el)->htmlOuter() |
| 查找子元素 | pq($el)->find('span') |
| 遍歷 | foreach (pq('a') as $el) { ... } |
php_dom 和 php_libxml 擴展phpQuery 以其極低的學習成本和強大的功能,成為 PHP 爬蟲、內容提取、模板渲染等場景的利器。對於熟悉 jQuery 的開發者幾乎零成本上手。