由於沒有PHPQuery的composer包安裝所以需要我們手動在我們的laravel項目中安裝加載PHPQuery,這里需要設置laravel的autoload->class map。
1、首先在app目錄下創建一個新的文件夾,命名libs(可自定義),在libs下再創建一個phpQuery文件夾
2、找到根目錄下的composer.json文件
3、找到composer.json中定義的
"autoload": { "classmap": [ "database", "app/libs/phpQuery" //加上 ], "psr-4": { "App\\": "app/" } },
4、運行終端,cd到項目路徑,執行
composer dumpautoload
然后就能在項目中愉快的使用phpQuery了,簡單的用法如下:
use phpQuery;
5、PHPQuery的使用
載入文檔(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相關資料,用法基本一致,只需要注意.與->的區別即可。