phpQuery Manual

    本文地址:http://tongxinmao.com/Article/Detail/id/132

    phpQuery Manual



    Basics


    phpQuery::newDocumentFileXHTML('my-xhtml.html')->find('p'); 

    $ul = pq('ul');


    Loading documents


    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) Read more about it on PHPSupport page

    phpQuery::newDocumentFileHTML($file, $charset = 'utf-8')

    phpQuery::newDocumentFileXHTML($file, $charset = 'utf-8')

    phpQuery::newDocumentFileXML($file, $charset = 'utf-8')

    phpQuery::newDocumentFilePHP($file, $contentType) Read more about it on PHPSupport page

    pq function


    pq($param, $context = null);


    pq(); function is equivalent of jQuery's $();. It's used for 3 type of things:


    Importing markup

    // Import into selected document: 

    // doesn't accept text nodes at beginning of input string 

    pq('<div/>') 

    // Import into document with ID from $pq->getDocumentID(): 

    pq('<div/>', $pq->getDocumentID()) 

    // Import into same document as DOMNode belongs to: 

    pq('<div/>', DOMNode) 

    // Import into document from phpQuery object: 

    pq('<div/>', $pq)


    Running queries

    // Run query on last selected document: 

    pq('div.myClass') 

    // Run query on document with ID from $pq->getDocumentID(): 

    pq('div.myClass', $pq->getDocumentID()) 

    // Run query on same document as DOMNode belongs to and use node(s)as root for query: 

    pq('div.myClass', DOMNode) 

    // Run query on document from phpQuery object 

    // and use object's stack as root node(s) for query: 

    pq('div.myClass', $pq)


    Wrapping DOMNodes with phpQuery objects

    foreach(pq('li') as $li) 

    // $li is pure DOMNode, change it to phpQuery object 

      pq($li);


    Selectors


    Basics


    #id Matches a single element with the given id attribute.

    element Matches all elements with the given name.

    .class Matches all elements with the given class.

    * Matches all elements.

    selector1, selector2, selectorN Matches the combined results of all the specified selectors.

    Hierarchy


    ancestor descendant Matches all descendant elements specified by "descendant" of elements specified by "ancestor".

    parent > child Matches all child elements specified by "child" of elements specified by "parent".

    prev + next Matches all next elements specified by "next" that are next to elements specified by "prev".

    prev ~ siblings Matches all sibling elements after the "prev" element that match the filtering "siblings" selector.

    Basic Filters


    :first Matches the first selected element.

    :last Matches the last selected element.

    :not(selector) Filters out all elements matching the given selector.

    :even Matches even elements, zero-indexed.

    :odd Matches odd elements, zero-indexed.

    :eq(index) Matches a single element by its index.

    :gt(index) Matches all elements with an index above the given one.

    :lt(index) Matches all elements with an index below the given one.

    :header Matches all elements that are headers, like h1, h2, h3 and so on.

    :animated Matches all elements that are currently being animated.

    Content Filters


    :contains(text) Matches elements which contain the given text.

    :empty Matches all elements that have no children (including text nodes).

    :has(selector) Matches elements which contain at least one element that matches the specified selector.

    :parent Matches all elements that are parents - they have child elements, including text.

    Visibility Filters


    none


    Attribute Filters


    [attribute] Matches elements that have the specified attribute.

    [attribute=value] Matches elements that have the specified attribute with a certain value.

    [attribute!=value] Matches elements that don't have the specified attribute with a certain value.

    [attribute^=value] Matches elements that have the specified attribute and it starts with a certain value.

    [attribute$=value] Matches elements that have the specified attribute and it ends with a certain value.

    [attribute*=value] Matches elements that have the specified attribute and it contains a certain value.

    [selector1selector2selectorN] Matches elements that have the specified attribute and it contains a certain value.

    Child Filters


    :nth-child(index/even/odd/equation) Matches all elements that are the nth-child of their parent or that are the parent's even or odd children.

    :first-child Matches all elements that are the first child of their parent.

    :last-child Matches all elements that are the last child of their parent.

    :only-child Matches all elements that are the only child of their parent.

    Forms


    :input Matches all input, textarea, select and button elements.

    :text Matches all input elements of type text.

    :password Matches all input elements of type password.

    :radio Matches all input elements of type radio.

    :checkbox Matches all input elements of type checkbox.

    :submit Matches all input elements of type submit.

    :image Matches all input elements of type image.

    :reset Matches all input elements of type reset.

    :button Matches all button elements and input elements of type button.

    :file Matches all input elements of type file.

    :hidden Matches all elements that are hidden, or input elements of type "hidden".

    Form Filters


    :enabled Matches all elements that are enabled.

    :disabled Matches all elements that are disabled.

    :checked Matches all elements that are checked.

    :selected Matches all elements that are selected.

    Attributes


    Example


    pq('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...


    Attr


    attr($name) Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned.

    attr($properties) Set a key/value object as properties to all matched elements.

    attr($key, $value) Set a single property to a value, on all matched elements.

    attr($key, $fn) Set a single property to a computed value, on all matched elements.

    removeAttr($name) Remove an attribute from each of the matched elements.

    Class


    addClass($class) Adds the specified class(es) to each of the set of matched elements.

    hasClass($class) Returns true if the specified class is present on at least one of the set of matched elements.

    removeClass($class) Removes all or the specified class(es) from the set of matched elements.

    toggleClass($class) Adds the specified class if it is not present, removes the specified class if it is present.

    HTML


    html() Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).

    html($val) Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

    Text


    text() Get the combined text contents of all matched elements.

    text($val) Set the text contents of all matched elements.

    Value


    val() Get the content of the value attribute of the first matched element.

    val($val) Set the value attribute of every matched element.

    val($val) Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

    Read more at Attributes section on jQuery Documentation Site.


    Traversing


    Example


    pq('div > p')->add('div > ul')->filter(':has(a)')->find('p:first')->nextAll()->andSelf()->...


    Filtering


    eq($index) Reduce the set of matched elements to a single element.

    hasClass($class) Checks the current selection against a class and returns true, if at least one element of the selection has the given class.

    filter($expr) Removes all elements from the set of matched elements that do not match the specified expression(s).

    filter($fn) Removes all elements from the set of matched elements that does not match the specified function.

    is($expr) Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.

    map($callback) Translate a set of elements in the jQuery object into another set of values in an array (which may, or may not, be elements).

    not($expr) Removes elements matching the specified expression from the set of matched elements.

    slice($start, $end) Selects a subset of the matched elements.

    Finding


    add($expr) Adds more elements, matched by the given expression, to the set of matched elements.

    children($expr) Get a set of elements containing all of the unique immediate children of each of the matched set of elements.

    contents() Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.

    find($expr) Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.

    next($expr) Get a set of elements containing the unique next siblings of each of the given set of elements.

    nextAll($expr) Find all sibling elements after the current element.

    parent($expr) Get a set of elements containing the unique parents of the matched set of elements.

    parents($expr) Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). The matched elements can be filtered with an optional expression.

    prev($expr) Get a set of elements containing the unique previous siblings of each of the matched set of elements.

    prevAll($expr) Find all sibling elements before the current element.

    siblings($expr) Get a set of elements containing all of the unique siblings of each of the matched set of elements. Can be filtered with an optional expressions.

    Chaining


    andSelf() Add the previous selection to the current selection.

    end() Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).

    Read more at Traversing section on jQuery Documentation Site.


    Manipulation


    Example


    pq('div.old')->replaceWith( pq('div.new')->clone() )->appendTo('.trash')->prepend('Deleted')->...


    Changing Contents


    html() Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).

    html($val) Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

    text() Get the combined text contents of all matched elements.

    text($val) Set the text contents of all matched elements.

    Inserting Inside


    append($content) Append content to the inside of every matched element.

    appendTo($content) Append all of the matched elements to another, specified, set of elements.

    prepend($content) Prepend content to the inside of every matched element.

    prependTo($content) Prepend all of the matched elements to another, specified, set of elements.

    Inserting Outside


    after($content) Insert content after each of the matched elements.

    before($content) Insert content before each of the matched elements.

    insertAfter($content) Insert all of the matched elements after another, specified, set of elements.

    insertBefore($content) Insert all of the matched elements before another, specified, set of elements.

    Inserting Around


    wrap($html) Wrap each matched element with the specified HTML content.

    wrap($elem) Wrap each matched element with the specified element.

    wrapAll($html) Wrap all the elements in the matched set into a single wrapper element.

    wrapAll($elem) Wrap all the elements in the matched set into a single wrapper element.

    wrapInner($html) Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

    wrapInner($elem) Wrap the inner child contents of each matched element (including text nodes) with a DOM element.

    Replacing


    replaceWith($content) Replaces all matched elements with the specified HTML or DOM elements.

    replaceAll($selector) Replaces the elements matched by the specified selector with the matched elements.

    Removing


    empty() Remove all child nodes from the set of matched elements.

    remove($expr) Removes all matched elements from the DOM.

    Copying


    clone() Clone matched DOM Elements and select the clones.

    clone($true) Clone matched DOM Elements, and all their event handlers, and select the clones.

    Read more at Manipulation section on jQuery Documentation Site.


    Ajax


    Example


    pq('#element')->load('http://somesite.com/page .inline-selector')->...


    Server Side Ajax


    Ajax, standing for Asynchronous JavaScript and XML is combination of HTTP Client and XML parser which doesn't lock program's thread (doing request in asynchronous way).


    phpQuery also offers such functionality, making use of solid quality Zend_Http_Client. Unfortunately requests aren't asynchronous, but nothing is impossible. For today, instead of XMLHttpRequest you always get Zend_Http_Client instance. API unification is planned.


    Cross Domain Ajax


    For security reasons, by default phpQuery doesn't allow connections to hosts other than actual $_SERVER['HTTP_HOST']. Developer needs to grant rights to other hosts before making an Ajax request.


    There are 2 methods for allowing other hosts


    phpQuery::ajaxAllowURL($url)

    phpQuery::ajaxAllowHost($host)

    // connect to google.com 

    phpQuery::ajaxAllowHost('google.com'); 

    phpQuery::get('http://google.com/ig'); 

    // or using same string 

    $url = 'http://google.com/ig'; 

    phpQuery::ajaxAllowURL($url); 

    phpQuery::get($url);


    Ajax Requests


    phpQuery::ajax($options) Load a remote page using an HTTP request.

    load($url, $data, $callback) Load HTML from a remote file and inject it into the DOM.

    phpQuery::get($url, $data, $callback) Load a remote page using an HTTP GET request.

    phpQuery::getJSON($url, $data, $callback) Load JSON data using an HTTP GET request.

    phpQuery::getScript($url, $callback) Loads, and executes, a local JavaScript file using an HTTP GET request.

    phpQuery::post($url, $data, $callback, $type) Load a remote page using an HTTP POST request.

    Ajax Events


    ajaxComplete($callback) Attach a function to be executed whenever an AJAX request completes. This is an Ajax Event.

    ajaxError($callback) Attach a function to be executed whenever an AJAX request fails. This is an Ajax Event.

    ajaxSend($callback) Attach a function to be executed before an AJAX request is sent. This is an Ajax Event.

    ajaxStart($callback) Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event.

    ajaxStop($callback) Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.

    ajaxSuccess($callback) Attach a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

    Misc


    phpQuery::ajaxSetup($options) Setup global settings for AJAX requests.

    serialize() Serializes a set of input elements into a string of data. This will serialize all given elements.

    serializeArray() Serializes all forms and form elements (like the .serialize() method) but returns a JSON data structure for you to work with.

    Options


    Detailed options description in available at jQuery Documentation Site.


    async Boolean

    beforeSend Function

    cache Boolean

    complete Function

    contentType String

    data Object, String

    dataType String

    error Function

    global Boolean

    ifModified Boolean

    jsonp String

    password String

    processData Boolean

    success Function

    timeout Number

    type String

    url String

    username String

    Read more at Ajax section on jQuery Documentation Site.


    Events


    Example


    pq('form')->bind('submit', 'submitHandler')->trigger('submit')->... 

    function submitHandler($e) { 

    print 'Target: '.$e->target->tagName; 

    print 'Bubbling ? '.$e->currentTarget->tagName; 

    }


    Server Side Events


    phpQuery support server-side events, same as jQuery handle client-side ones. On server there isn't, of course, events such as mouseover (but they can be triggered).


    By default, phpQuery automatically fires up only change event for form elements. If you load WebBrowser plugin, submit and click will be handled properly - eg submitting form with inputs' data to action URL via new Ajax request.


    $this (this in JS) context for handler scope isn't available. You have to use one of following manually:


    $event->target

    $event->currentTarget

    $event->relatedTarget

    Page Load


    none


    Event Handling


    bind($type, $data, $fn) Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.

    one($type, $data, $fn) Binds a handler to one or more events to be executed once for each matched element.

    trigger($type , $data ) Trigger a type of event on every matched element.

    triggerHandler($type , $data ) This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.

    unbind($type , $data ) This does the opposite of bind, it removes bound events from each of the matched elements.

    Interaction Helpers


    none


    Event Helpers


    change() Triggers the change event of each matched element.

    change($fn) Binds a function to the change event of each matched element.

    submit() Trigger the submit event of each matched element.

    submit($fn) Bind a function to the submit event of each matched element.

    Read more at Events section on jQuery Documentation Site.


    Utilities


    User Agent


    none


    Array and Object operations


    phpQuery::each($object, $callback) A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

    phpQuery::grep($array, $callback, $invert) Filter items out of an array, by using a filter function.

    phpQuery::makeArray($obj) Turns an array-like object into a true array.

    phpQuery::map($array, $callback) Translate all items in an array to another array of items.

    phpQuery::inArray($value, $array) Determine the index of the first parameter in the Array (-1 if not found).

    phpQuery::unique($array) Remove all duplicate elements from an array of elements.

    Test operations


    phpQuery::isFunction($obj) Determine if the parameter passed is a function.

    String operations


    phpQuery::trim($str) Remove the whitespace from the beginning and end of a string.

    Read more at Utilities section on jQuery Documentation Site.


    PluginsClientSidePorts


    In Issue Tracker there is a list of plugins which are planned to be ported.


    JSON


    Port of JSON plugin.


    $jsonString = phpQuery::toJSON( pq('form')->serializeArray() ); 

    $array = phpQuery::parseJSON('{"foo": "bar"}');


    PHPSupport


    Although phpQuery is a jQuery port, there is extensive PHP-specific support.


    Class Interfaces


    phpQuery implements some of Standard PHP Library (SPL) interfaces.


    Iterator


    Iterator interface allows looping objects thou native PHP foreach loop. Example:


    // get all direct LI elements from UL list of class 'im-the-list' 

    $LIs = pq('ul.im-the-list > li'); 

    foreach($LIs as $li) { 

      pq($li)->addClass('foreached'); 

    }


    Now there is a catch above. Foreach loop doesn't return phpQuery object. Instead it returns pure DOMNode. That's how jQuery does, because not always you need phpQuery when you found interesting nodes.


    Array Access


    If you like writing arrays, with phpQuery you can still do it, thanks to the ArrayAccess interface.


    $pq = phpQuery::newDocumentFile('somefile.html'); 

    // print first list outer HTML 

    print $pq['ul:first']; 

    // change INNER HTML of second LI directly in first UL 

    $pq['ul:first > li:eq(1)'] = 'new inner html of second LI directly in first UL'; 

    // now look at the difference (outer vs inner) 

    print $pq['ul:first > li:eq(1)']; 

    // will print <li>new inner html of second LI directly in first UL</li>


    Countable


    If used to do count($something) you can still do this that way, instead of eg pq('p')->size().


    // count all direct LIs in first list 

    print count(pq('ul:first > li'));


    Callbacks


    There is a special Callbacks wiki section, to which you should refer to.


    PHP Code Support


    Opening PHP files as DOM


    PHP files can be opened using phpQuery::newDocumentPHP($markup) or phpQuery::newDocumentFilePHP($file). Such files are visible as DOM, where:


    PHP tags beetween DOM elements are available (queryable) as <php> ...code... </php>

    PHP tags inside attributes are HTML entities

    PHP tags between DOM element's attributes are not yet supported

    Inputting PHP code


    Additional methods allows placing PHP code inside DOM. Below each method visible is it's logic equivalent.


    attrPHP($attr, $code)

    attr($attr, "<?php $code ?>")

    addClassPHP($code)

    addClass("<?php $code ?>")

    beforePHP($code)

    before("<?php $code ?>")

    afterPHP($code)

    after("<?php $code ?>")

    prependPHP($code)

    prepend("<?php $code ?>")

    appendPHP($code)

    append("<?php $code ?>")

    php($code)

    html("<?php $code ?>")

    wrapAllPHP($codeBefore, $codeAfter)

    wrapAll("<?php $codeBefore?><?php $codeAfter ?>")

    wrapPHP($codeBefore, $codeAfter)

    wrap("<?php $codeBefore?><?php $codeAfter ?>")

    wrapInnerPHP($codeBefore, $codeAfter)

    wrapInner("<?php $codeBefore?><?php $codeAfter ?>")

    replaceWithPHP($code)

    replaceWith("<?php $code ?>")

    Outputting PHP code


    Code inserted with methods above won't be returned as valid (runnable) using classic output methods such as html(). To make it work, php() method without parameter have to be used. Optionaly phpQuery::markupToPHP($markup) can activate tags in string outputed before. REMEMBER Outputing runnable code and placing it on webserver is always dangerous


    MultiDocumentSupport


    What MultiDocumentSupport is


    support for working on several documents in same time

    easy importing of nodes from one document to another

    pointing document thought

    phpQuery object

    DOMNode object

    DOMDocument object

    internal document ID

    last created (or selected) document is assumed to be default in pq();

    What MultiDocumentSupport is NOT


    it's not possible to fetch nodes from several document in one query

    it's not possible to operate on nodes from several document in one phpQuery object

    Example


    // 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);


    Static Methods


    phpQuery::newDocument($html) Creates new document from markup

    phpQuery::newDocumentFile($file) Creates new document from file

    phpQuery::getDocument($id = null) Returns phpQueryObject containing document with id $id or default document (last created/selected)

    phpQuery::selectDocument($id) Sets default document to $id

    phpQuery::unloadDocuments($id = null) Unloades all or specified document from memory

    phpQuery::getDocumentID($source) Returns $source's document ID

    phpQuery::getDOMDocument($source) Get DOMDocument object related to $source

    Object Methods


    $pq->getDocument() Returns object with stack set to document root

    $pq->getDocumentID() Get object's Document ID

    $pq->getDocumentIDRef(&$documentID) Saves object's DocumentID to $var by reference

    $pq->unloadDocument() Unloads whole document from memory


    上一篇:汉王笔USB描述符
    下一篇:HTML5 活动宣传页「My Flyme 独家记忆」开发实践总结