简介
如何在php中方便地解析html代码,估计是每个phper都会遇到的问题。用phpQuery就可以让php处理html代码像jQuery一样方便。
项目地址:https://code.google.com/p/phpquery/
github地址:https://github.com/TobiaszCudnik/phpquery
DEMO
下载库文件: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 class="thumb" id="Thumb-13164-3640" style="position: absolute; left: 0px; top: 0px;">
<a href="/Spiderman-City-Drive">
<img src="/thumb/12/Spiderman-City-Drive.jpg" alt="">
<span class="GameName" id="GameName-13164-3640" style="display: none;">Spiderman City Drive</span>
<span class="GameRating" id="GameRating-13164-3640" style="display: none;">
<span style="width: 68.14816px;"></span>
</span>
</a>
</div>
<div class="thumb" id="Thumb-13169-5946" style="position: absolute; left: 190px; top: 0px;">
<a href="/Spiderman-City-Raid">
<img src="/thumb/12/Spiderman-City-Raid.jpg" alt="">
<span class="GameName" id="GameName-13169-5946" style="display: none;">Spiderman - City Raid</span>
<span class="GameRating" id="GameRating-13169-5946" style="display: none;">
<span style="width: 67.01152px;"></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;
新闻热点
疑难解答