$query php,phpQuery让php处理html代码像jQuery一样方便
簡介
如何在php中方便地解析html代碼,估計是每個phper都會遇到的問題。用phpQuery就可以讓php處理html代碼像jQuery一樣方便。
DEMO
我下的是onefile版:phpQuery-0.9.5.386-onefile.zip
然后在項目中引用。
html文件test.html:
???????
Spiderman City Drive
???????
Spiderman - City Raid
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()
);
foreach (pq('a') as $t) {
$href = $t -> getAttribute('href');
$data['href'][] = $href;
}
foreach (pq('img') as $img) {
$data['img'][] = $domain . $img -> getAttribute('src');
}
foreach (pq('.GameName') as $name) {
$data['name'][] = $name -> nodeValue;
}
var_dump($data);
?>
上面的代碼中包含了取屬性和innerText內容(通過nodeValue取)。
輸出:
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 'http://www.gahe.com/Spiderman-City-Drive' (length=40)
1 => string 'http://www.gahe.com/Spiderman-City-Raid' (length=39)
'img' =>
array (size=2)
0 => string 'http://www.gahe.com/thumb/12/Spiderman-City-Drive.jpg' (length=53)
1 => string 'http://www.gahe.com/thumb/12/Spiderman-City-Raid.jpg' (length=52)
強大的是pq選擇器,語法類似jQuery,很方便。
總結
以上是生活随笔為你收集整理的$query php,phpQuery让php处理html代码像jQuery一样方便的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 电梯程序设计,教你写出京东电梯式
- 下一篇: java继承接口和泛型,JavaSE习题