微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

phpQuery让php处理html代码像jQuery一样方便

简介

如何在PHP中方便地解析HTML代码,估计是每个PHPer都会遇到的问题。用PHPQuery就可以让PHP处理HTML代码像jQuery一样方便。

项目地址:

github地址:

DEMO

下载库文件

我下的是onefile版:phpQuery-0.9.5.386-onefile.zip

官方demo:

然后在项目中引用。

html文件test.html

代码如下:

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

原文地址:https://www.jb51.cc/php/22925.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐