$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,很方便。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值