前言
為什么使用phpQuery
-
phpQuery是基於php5新添加的DOMDocument。而DOMDocument則是專門用來處理html/xml。它提供了強大的xpath選擇器及其他很多html/xml操作函數,使得處理html/xml起來非常方便。
-
尤其對於新手,看到一堆”不知所雲”的字符評湊在一起,有種腦袋都要炸了的感覺。如果要分離的對象沒有太明顯的特征,正則寫起來更是麻煩。
-
學習成本低,jQuery是PHP程序員的標配,那么懂jQuery的話,是可以無縫銜接的,學習成本幾乎為0。選擇器,節點,節點信息,over
Demo
<?php require("phpQuery.php");//導入phpQuery庫 $html = phpQuery::newDocumentFile("https://segmentfault.com/tags"); $hrefList = pq(".tag"); //獲取標簽為a的所有對象$(".tag") foreach ($hrefList as $href) {
//echo pq($href)->attr('date-original-title').<br>; echo $href->getAttribute("data-original-title"),"<br>"; }
使用
官方文檔地址:https://code.google.com/archive/p/phpquery/wikis
一、phpQuery的hello word!
下面簡單舉例:
include 'phpQuery.php';
phpQuery::newDocumentFile('http://www.phper.org.cn');
echo pq("title")->text(); // 獲取網頁標題
echo pq("div#header")->html(); // 獲取id為header的div的html內容
上例中第一行引入phpQuery.PHP文件,
第二行通過newDocumentFile加載一個文件,
第三行通過pq()函數獲取title標簽的文本內容,
第四行獲取id為header的div標簽所包含的HTML內容。
主要做了兩個動作,即加載文件和讀取文件內容。
二、載入文檔(loading documents)
加載文檔主要通過phpQuery::newDocument來進行操作,其作用是使得phpQuery可以在服務器預先讀取到指定的文件或文本內容。
主要的方法包括:
phpQuery::newDocument($html, $contentType = null)
phpQuery::newDocumentFile($file, $contentType = null)
phpQuery::newDocumentHTML($html, $charset = ‘utf-8′)
phpQuery::newDocumentXHTML($html, $charset = ‘utf-8′)
phpQuery::newDocumentXML($html, $charset = ‘utf-8′)
phpQuery::newDocumentPHP($html, $contentType = null)
phpQuery::newDocumentFileHTML($file, $charset = ‘utf-8′)
phpQuery::newDocumentFileXHTML($file, $charset = ‘utf-8′)
phpQuery::newDocumentFileXML($file, $charset = ‘utf-8′)
phpQuery::newDocumentFilePHP($file, $contentType)
三、pq()函數用法
pq()函數的用法是phpQuery的重點,主要分兩部分:即選擇器和過濾器
【選擇器】
要了解phpQuery選擇器的用法,建議先了解jQuery的語法
最常用的語法包括有:
pq('#id'):即以#號開頭的ID選擇器,用於選擇已知ID的容器所包括的內容
pq('.classname'):即以.開頭的class選擇器,用於選擇class匹配的容器內容
pq('parent > child'):選擇指定層次結構的容器內容,如:pq('.main > p')用於選擇class=main容器的所有p標簽
更多的語法請參考jQuery手冊
【過濾器】
主要包括::first,:last,:not,:even,:odd,:eq(index),:gt(index),:lt(index),:header,:animated等
如:
pq('p:last'):用於選擇最后一個p標簽
pq('tr:even'):用於選擇表格中偶然行
【使用phpQuery對象對DOM節點進行原型化操作】
foreach(pq('li') as $li) // $li是純DOM節點, 將它變為phpQuery對象: pq($li);
四、phpQuery連貫操作
pq()函數返回的結果是一個phpQuery對象,可以對返回結果繼續進行后續的操作,例如:
pq('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...
詳情請查閱jQuery相關資料,用法基本一致,只需要注意.與->的區別即可。