一、phpQuery的hello word!
下面簡單舉例:
include 'phpQuery.php';
phpQuery::newDocumentFile('http://www.phper.org.cn');
echo pq("title")->text(); // 獲取網(wǎng)頁標題
echo pq("div#header")->html(); // 獲取id為header的div的html內容
上例中第一行引入phpQuery.PHP文件惯悠,
第二行通過newDocumentFile加載一個文件鞋仍,
第三行通過pq()函數(shù)獲取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()函數(shù)用法
pq()函數(shù)的用法是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()函數(shù)返回的結果是一個phpQuery對象革为,可以對返回結果繼續(xù)進行后續(xù)的操作哗伯,例如:
pq('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...
詳情請查閱jQuery相關資料,用法基本一致篷角,只需要注意.與->的區(qū)別即可焊刹。