phpQuery


服务器端的jQuery,抓取网页的特定的信息  phpQuery方便快捷
官网 //code.google.com/p/phpquery
phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library.Library is written in PHP5 and provides additional Command Line Interface (CLI).
步骤
1.引入phpquery类库include 'phpQuery/phpQuery.php';
2 加载网页连接或文档 phpQuery::newDocument()
常用方法
phpQuery::newDocumentFile($file,$contentType = null)
$file可以是一个网址地址或html文件路径
$contentType为空,则根据文档检测编码
检测失败,则对于text/html类型文档自动赋予utf-8编码
phpQuery::newDocument($html),$html是html格式的字符串或代码
header("Content-Type: text/html;charset=utf-8");
require('phpQuery/phpQuery.php');
$eg1=phpQuery::newDocumentFile("test.htm");
$eg2=phpQuery::newDocumentFile("http://www.baidu.com");
//echo htmlentities($eg1,ENT_QUOTES,"UTF-8");//htmlentities()函数可以输出原始html代码

$html="<div><ul><li>第一行</li><li>第二行</li></ul></div";
$eg3=phpQuery::newDocument($html);//输入入参数为html
phpQuery::newDocument($file)初始加载时返回html串
用html操作句柄函数pq() 筛选提取内容
3 pq用法
pq($param, $context = null);
pq()是phpQuery重点
pq($xpath,$DocumentID)第一个$xpath是通过html标签/类/id等定位到某一元素
$DocumentID 看做为一个指针,指向查询html文档(就是phpQuery::newDocumentFile($file)的返回结果
如:$eg1或$eg2或$eg3 也就是html的context),同时对多个文档操作时,用这个参数,
如果没有给出,会自动邻近匹配匹配,只对一个文档操作省略,用pq($xpath)即可,pq()相当 jQuery的$()

主要分两部分即选择器和过滤器
4 选择器
#id 根据给定的ID属性匹配单个元素
element 根据给定的名称匹配所有符合的元素
.class 根据给定的class匹配所有的元素
* 选择所有元素
selector1, selector2, selectorN 根据所有制定的选择器匹配结合结果选择结果是取并集
#id                     pq("#myDiv");
element                 pq("div");
.class                  pq(".myClass");
*                       pq("*")
selector1,selectorN     pq("div,span,p.myClass")
层次选择器
ancestor descendant 匹配由先祖指定的元素的后代指定的所有后代元素
parent > child 匹配由父元素指定的子元素指定的所有子元素
prev + next 根据指定的”next”和指定的”prev”匹配所有的下一个元素
prev ~ siblings 匹配根据”prev” 元素的 所有相邻元素
ancestor descendant     pq("form input")
parent > child          pq("form > input")
prev + next             pq("label + input")
prev ~ siblings         pq("form ~ input")
5 基础过滤
:first 匹配第一个被选择的元素
:last 匹配最后一个被选择的元素
:not(selector) 匹配所有不是被选择的元素
:even 匹配所有被选择的偶数元素,0索引
:odd 匹配所有被选择的奇数元素,0索引
:eq(index) 匹配等同于给定的索引的元素
:gt(index) 匹配大于给定的索引的元素
:lt(index) 匹配小于给定的索引的元素
:header 匹配所有header元素,如h1,h2,h3等
:animated 匹配正在进行动画效果的元素
:first                  pq("tr:first")
:last                   pq("tr:last")
:not(selector)          pq("input:not(:checked)")
:even                   pq("tr:even")
:odd                    pq("tr:odd")
:eq(index)              pq("tr:eq(1)")
:gt(index)              pq("tr:gt(0)")
:lt(index)              pq("tr:lt(2)")
:header                 pq(":header").css("background", "#EEE");
内容过滤
:contains(text) 匹配包含指定文本的元素
:empty 匹配所有无子节点的元素(包括文本节点)
:has(selector) 匹配至少包含一个对于给定选择器的元素
:parent 匹配所有父元素 - 拥有子元素的,包括文本
:contains(text)         pq("div:contains('John')")
:empty                  pq("td:empty")
:has(selector)          pq("div:has(p)").addClass("test");
:parent                 pq("td:parent")
属性过滤
[attribute] 匹配给定属性的元素
[attribute=value] 给定属性等于确定值的元素
[attribute!=value] 给定属性不等于确定值的元素
[attribute^=value] 给定属性是确定值开始的元素
[attribute$=value] 给定属性是确定值结尾的元素
[attribute*=value] 给定属性包含确定值的元素
[selector1selector2selectorN] 给定属性并且包含确定值的元素
[attribute]             pq("div[id]")
[attribute=value]       pq("input[name='newsletter']").attr("checked", true);
[attribute!=value]      pq("input[name!='newsletter']").attr("checked", true);
[attribute^=value]      pq("input[name^='news']")
[attribute$=value]      pq("input[name$='letter']")
[attribute*=value]      pq("input[name*='man']")
[selector1][selectorN]  pq("input[id][name$='man']")
子元素过滤
:nth-child(index/even/odd/equation) 匹配所有是父元素的第n个的子元素,或父元素的偶数或奇数子元素
:first-child 父元素的第一个的子元素
:last-child 父元素的最后一个的子元素
:only-child 父元素唯一子元素的子元素
:nth-child(index/even/odd/equation) pq("ul li:nth-child(2)")
:first-child  pq("ul li:first-child")
:last-child  pq("ul li:last-child")
:only-child  pq("ul li:only-child")
基于表单
:input 匹配input, textarea, select和button元素
:text 类型为text的input元素
:password 类型为password的input元素
:radio 类型为radio的input元素
:checkbox 类型为checkbox的input元素
:submit 类型为submit的input元素
:image 类型为image的input元素
:reset 类型为reset的input元素
:button 类型为button的input元素和button元素
:file 类型为file的input元素
:hidden 类型为hidden的input元素或者其他hidden元素
:input                  pq(":input")
:text                   pq(":text")
:password               pq(":password")
:radio                  pq(":radio")
:checkbox               pq(":checkbox")
:submit                 pq(":submit")
:image                  pq(":image")
:reset                  pq(":reset")
:button                 pq(":button")
:file                   pq(":file")
:hidden                 pq("tr:hidden")
表单过滤
:enabled 可用元素
:disabled 不可用元素
:checked 被勾选的元素
:selected被选择的元素
:enabled  pq("input:enabled")
:disabled pq("input:disabled")
:checked   pq("input:checked")
:selected pq("select option:selected")
attr属性获取
attr($name) 访问第一个给名称的元素的属性 这个方法可以很轻易地取得第一个匹配到的元素的属性值 如果这个元素没有对应名称的属性则返回undefined
attr($properties) 对于所有匹配到的元素设置对应属性
attr($key, $value) 对于匹配到的元素设置一个属性和对应值
attr($key, $fn) 对于匹配到的元素设置一个属性和需要计算的值
removeAttr($name) 对匹配到的元素移除给定名称的属性
addClass($class) 对匹配到的元素添加一个给定的类
hasClass($class) 如果有至少一个匹配到的元素包含给定的类则返回true
removeClass($class) 对匹配到的元素移除给定名称的类
toggleClass($class) 对匹配到的元素,如果类不存在则添加,如果存在则移除
attr                    pq("img")->attr("src");
attr(properties)        pq("img")->attr({ src: "test.jpg", alt: "Test Image" });
attr(key,value)         pq("img")->attr("src","test.jpg");
attr(key,fn)            pq("img")->attr("title", function() { return this.src });
removeAttr(name)        pq("img")->removeAttr("src");
addClass(class)         pq("p")->addClass("selected");
removeClass(class)      pq("p")->removeClass("selected");
toggleClass(class)      pq("p")->toggleClass("selected");
HTML获取
html() 获取第一个匹配到的元素的html内容(innerHTML) 这个方法不适用于XML文本(但适用于XHTML )
html($val) 对匹配到的元素设置html内容 这个方法不适用于XML文本(但适用于XHTML )
html()                  pq("div")->html();
html(val)               pq("div")->html("<p>Hello Again</p>");
text获取
text() 获取匹配到的所有元素的文本内容
text($val) 对匹配到的所有元素设置文本内容
text()                  pq("p")->text();
text(val)               pq("p")->text("<b>Some</b> new text.");
Value 获取
val() 获取匹配到的第一个元素的value属性的值
val($val) 对匹配到的元素设置value值 val($val) 所有的Checks, selects, radio buttons, checkboxes,和select options都会设置相应给定的值
val()                   pq("input")->val();
val(val)                pq("input")->val("hello world!");
\*筛选*\
eq(index)               pq("p")->eq(1)
hasClass(class)         pq("div")->hasClass("protected")
filter(expr)            pq("p")->filter(".selected")
filter(fn)   pq("p")->filter(function($index) {return pq("ol", pq($index))->size() == 0;});
is(expr)                pq("input[type='checkbox']")->parent()->is("form")
map(callback) pq("p")->append(pq("input").map(function(){return pq(this)->val();})->get()->join(", "));
not(expr)               pq("p")->not(pq("#selected")[0])
slice(start,[end])      pq("p")->slice(0, 1)->wrapInner("<b></b>");
add(expr)               pq("p")->add("span")
children([expr])        pq("div")->children()
contents()              pq("p")->contents()->not("[@nodeType=1]").wrap("<b/>");
find(expr)              pq("p")->find("span")
next([expr])            pq("p")->next()
nextAll([expr])         pq("div:first")->nextAll()->addClass("after");
parent([expr])          pq("p")->parent()
parents([expr])         pq("span")->parents()
prev([expr])            pq("p").prev()
prevAll([expr])         pq("div:last")->prevAll()->addClass("before");
siblings([expr])        pq("div")->siblings()
andSelf()               pq("div")->find("p")->andSelf()->addClass("border");
end()                   pq("p")->find("span")->end()
文档处理
append(content)         pq("p")->append("<b>Hello</b>");
appendTo(content)       pq("p")->appendTo("#foo");
prepend(content)        pq("p")->prepend("<b>Hello</b>");
prependTo(content)      pq("p")->prependTo("#foo");
after(content)          pq("p")->after("<b>Hello</b>");
before(content)         pq("p")->before("<b>Hello</b>");
insertAfter(content)    pq("p")->insertAfter("#foo");
insertBefore(content)   pq("p")->insertBefore("#foo");
wrap(html)              pq("p")->wrap("<div class='wrap'></div>");
wrap(elem)              pq("p")->wrap(pq("#content"));
wrapAll(html)           pq("p")->wrapAll("<div></div>");
wrapAll(elem)           pq("p")->wrapAll(pq("#content"));
wrapInner(html)         pq("p")->wrapInner("<b></b>");
wrapInner(elem)         pq("p")->wrapInner(pq(".content"));
replaceWith(content)    pq("p")->replaceWith("<b>Paragraph. </b>");
replaceAll(selector)    pq("<b>Paragraph. </b>")->replaceAll("p");
empty()                 pq("p")->empty();
remove([expr])          pq("p")->remove();
clone()                 pq("b")->clone()->prependTo("p");
clone(true)             pq("button")->clone(true)->insertAfter(pq("b"))
phpQuery基于php5的DOMDocument
DOMDocument 专门处理html/xml
xpath选择器及html/xml操作函数,使得处理html/xml起来非常方便
那为什么不直接使用呢
官网的函数列表 太多了看花眼 不好记
//www.php.net/manual/en/class.domdocument.php
DOMDocument extends DOMNode {

public readonly string $actualEncoding ;
public readonly DOMConfiguration $config ;
public readonly DOMDocumentType $doctype ;
public readonly DOMElement $documentElement ;
public string $documentURI ;
public string $encoding ;
public bool $formatOutput ;
public readonly DOMImplementation $implementation ;
public bool $preserveWhiteSpace = TRUE ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = TRUE ;
public bool $substituteEntities ;
public bool $validateOnParse = FALSE ;
public string $version ;
public readonly string $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;

public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;

public __construct ([ string $version [, string $encoding ]] )
public createAttribute ( string $name ) : DOMAttr
public createAttributeNS ( string $namespaceURI , string $qualifiedName ) : DOMAttr
public createCDATASection ( string $data ) : DOMCDATASection
public createComment ( string $data ) : DOMComment
public createDocumentFragment ( void ) : DOMDocumentFragment
public createElement ( string $name [, string $value ] ) : DOMElement
public createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] ) : DOMElement
public createEntityReference ( string $name ) : DOMEntityReference
public createProcessingInstruction ( string $target [, string $data ] ) : DOMProcessingInstruction
public createTextNode ( string $content ) : DOMText
public getElementById ( string $elementId ) : DOMElement
public getElementsByTagName ( string $name ) : DOMNodeList
public getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList
public importNode ( DOMNode $importedNode [, bool $deep = FALSE ] ) : DOMNode
public load ( string $filename [, int $options = 0 ] ) : mixed
public loadHTML ( string $source [, int $options = 0 ] ) : bool
public loadHTMLFile ( string $filename [, int $options = 0 ] ) : bool
public loadXML ( string $source [, int $options = 0 ] ) : mixed
public normalizeDocument ( void ) : void
public registerNodeClass ( string $baseclass , string $extendedclass ) : bool
public relaxNGValidate ( string $filename ) : bool
public relaxNGValidateSource ( string $source ) : bool
public save ( string $filename [, int $options = 0 ] ) : int
public saveHTML ([ DOMNode $node = NULL ] ) : string
public saveHTMLFile ( string $filename ) : int
public saveXML ([ DOMNode $node [, int $options = 0 ]] ) : string
public schemaValidate ( string $filename [, int $flags = 0 ] ) : bool
public schemaValidateSource ( string $source [, int $flags ] ) : bool
public validate ( void ) : bool
public xinclude ([ int $options = 0 ] ) : int

public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}