小兔网

为什么使用phpQuery

  • phpQuery是基于php5新添加的DOMDocument。而DOMDocument则是专门用来处理html/xml。它提供了强大的xpath选择器及其他很多html/xml操作函数,使得处理html/xml起来非常方便。
  • 尤其对于新手,看到一堆”不知所云”的字符评凑在一起,有种脑袋都要炸了的感觉。如果要分离的对象没有太明显的特征,正则写起来更是麻烦。
  • 学习成本低,jQuery是PHP程序员的标配,那么懂jQuery的话,是可以无缝衔接的,学习成本几乎为0。选择器,节点,节点信息,over
获取SF的所有标签名称https://segmentfault.com/tags,审查元素,得到部分标签属性。<a class="tag" data-original-title="负载均衡">负载均衡</a>

Demo

<?phprequire("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相关资料,用法基本一致,只需要注意.与->的区别即可。