《PHP實戰:phpQuery讓php處理html代碼像jQuery一樣方便》要點:
本文介紹了PHP實戰:phpQuery讓php處理html代碼像jQuery一樣方便,希望對您有用。如果有疑問,可以聯系我們。
簡介PHP實例
如安在php中方便地解析html代碼,估計是每個phper都會遇到的問題.用phpQuery就可以讓php處理html代碼像jQuery一樣方便.PHP實例
項目地址:https://code.google.com/p/phpquery/PHP實例
github地址:https://github.com/TobiaszCudnik/phpqueryPHP實例
DEMOPHP實例
下載庫文件:https://code.google.com/p/phpquery/downloads/listPHP實例
我下的是onefile版:phpQuery-0.9.5.386-onefile.zipPHP實例
官方demo:https://code.google.com/p/phpquery/source/browse/branches/dev/demo.phpPHP實例
然后在項目中引用.PHP實例
html文件test.html:PHP實例
代碼如下:
<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實例
代碼如下:
<?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取).PHP實例
輸出:PHP實例
代碼如下:
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實例
維易PHP培訓學院每天發布《PHP實戰:phpQuery讓php處理html代碼像jQuery一樣方便》等實戰技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養人才。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/12820.html