phpQuery的用法

一、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連貫操作

pq()函數返回的結果是一個phpQuery對象,可以對返回結果繼續進行後續的操作,例如:

 pq('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...

詳情請查閱jQuery相關資料,用法基本一致,只需要注意.與->的區別即可。


發佈了40 篇原創文章 · 獲贊 16 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章