首页 > 编程 > PHP > 正文

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

2020-03-22 20:18:20
字体:
来源:转载
供稿:网友
简介如何在php中方便地解析html代码,估计是每个phper都会遇到的问题。用phpQuery就可以让php处理html代码像jQuery一样方便。项目地址:https://code.google.com/p/phpquery/github地址:https://github.com/TobiaszCudnik/phpqueryDEMO下载库文件:https://code.google.com/p/phpquery/downloads/list我下的是onefile版:phpQuery-0.9.5.386-onefile.zip官方demo:https://code.google.com/p/phpquery/source/browse/branches/dev/demo.php然后在项目中引用。html文件test.html:复制代码 代码如下:
div id="Thumb-13164-3640"
a href="/Spiderman-City-Drive"
img src="/thumb/12/Spiderman-City-Drive.jpg" alt=""
span id="GameName-13164-3640" Spiderman City Drive /span
span id="GameRating-13164-3640"
span /span
/span
/a
/div
div id="Thumb-13169-5946"
a href="/Spiderman-City-Raid"
img src="/thumb/12/Spiderman-City-Raid.jpg" alt=""
span id="GameName-13169-5946" Spiderman - City Raid /span
span 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()
);
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,很方便。PHP教程

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表