依赖
PHP5以上、PHP5 DOM扩展、Zend Framework
PHP 5 DOM扩展是默认编译到内核的,这个不会有问题,phpQuery实际是它的二次封装。phpQuery之所以用到ZF是因为它使用了ZF的类库去模拟一个浏览器,它可以用来自动提交表单等交互操作。
Basics
1装载文档
phpQuery::newDocument($html, $contentType = null) Creates new document from markup. If no $contentType, autodetection is made (based on markup). If it fails, text/html in utf-8 is used. phpQuery::newDocumentFile($file, $contentType = null) Creates new document from file. Works like newDocument() 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)
事实上这里只有两类,一个是从标签(字符串)装载文档,另一个是从文件(URL)转载。文档的装载有两个参数需要确定,一个是字符编码,一个是内容类型,所谓内容类型就是指文档是HTML、XHTML、XML或是PHP。在newDocument 和 newDocumentFile函数中可以指定装载内容的类型,字符编码自动检测确定了。它们分别有对应的自定类型的版本,比如newDocumentHTML 和 newDocumentFileHTML。
2 pq函数
模拟jQuery中的$()函数
//插入标签
pq('<div/>')
pq('<div/>', $pq->getDocumentID())
pq('<div/>', DOMNode)
pq('<div/>', $pq)
//查询
pq('div.myClass')
pq('div.myClass', $pq->getDocumentID())
pq('div.myClass', DOMNode)
pq('div.myClass', $pq)
//用phpQuery对象包装DOMNodes
foreach(pq('li') as $li)
// $li is pure DOMNode, change it to phpQuery object
pq($li);
一般查询 和 包装是常用操作,插入一般使用更加直观的操作方法。
Ported jQuery section
这部分一共有8个主题,选择器 属性 过滤 文档处理 Ajax 事件 工具(一些常用函数) 插件接口,对应到jQuery,phpQuery缺少CSS 和 效果(也没有存在必要),用法上,高度类似。不过服务器端的Ajax 和 事件有点费解。
服务器端的Ajax实现 事实上是在服务器上模拟一个浏览器,它的实现是依赖Zend_Http_Client。
这部分具体的内容需要参考详细文档。
PHP Support
Command Line Interface
Multi document support 多文档支持
可以同时操作多个文档,最后创建或选择的文档在pq()函数中默认使用。
// first three documents are wrapped inside phpQuery
$doc1 = phpQuery::newDocumentFile('my-file.html');
$doc2 = phpQuery::newDocumentFile('my-file.html');
$doc3 = phpQuery::newDocumentFile('my-other-file.html');
// $doc4 is plain DOMDocument
$doc4 = new DOMDocument;
$doc4->loadHTMLFile('my-file.html');
// find first UL list in $doc1
$doc1->find('ul:first')
// append all LIs from $doc2 (node import)
->append( $doc2->find('li') )
// append UL (with new LIs) into $doc3 BODY (node import)
->appendTo( $doc3->find('body') );
// this will find all LIs from $doc3
// thats because it was created as last one
pq('li');
// this will find all LIs inside first UL in $doc2 (context query)
pq('li', $doc2->find('ul:first')->get());
// this will find all LIs in whole $doc2 (not a context query)
pq('li', $doc2->find('ul:first')->getDocumentID());
// this will transparently load $doc4 into phpQuery::$documents
// and then all LIs will be found
// TODO this example must be verified
pq('li', $doc4);
基本上,phpQuery还是DOM操作部分比较常用,其它的比如Ajax等部分使用起来还是多有别扭。
本文介绍phpQuery的基本使用方法,包括文档加载方式、pq函数的使用技巧及多文档操作支持等内容。phpQuery是一款PHP版本的jQuery,它支持从HTML、XHTML、XML或PHP文件加载文档,并提供了多种实用的方法进行DOM节点的查询与操作。
2万+

被折叠的 条评论
为什么被折叠?



