Table of Contents
This is a test page
Home Backend Development PHP Tutorial QueryPath -- PHP 中的 jQuery

QueryPath -- PHP 中的 jQuery

Jun 23, 2016 pm 02:31 PM

官方主页  http://querypath.org/

QP API 手册  http://api.querypath.org/docs/

QueryPath(QP)库 在 PHP 中实现了类似于 jQuery 的效果,用它还可以方便地处理 XML HTML...功能太强大了!!!

A QueryPath Tutorial(一个简易说明)

QueryPath makes use of method chaining to provide a concise suite of tools for manipulating a DOM.

The basic principle of method chaining is that each method returns an object upon which additional methods can be called. In our case, the QueryPath object usually returns itself.

Let's take a look at an example to illustrate:

                          <p class="sycode">                              $qp               =        qp(QueryPath       ::       HTML_STUB);        //        Generate a new QueryPath object.(创建一个 QP 对象)              $qp2               =               $qp       ->       find(       '       body       '       );        //        Find the body tag.(找到 "body" 标签)// Now the surprising part:(请看下面让你惊奇的地方)              if        (       $qp               ===               $qp2       ) {        //        This will always get printed.(它总是会这样输出)                      print               "       MATCH       "       ;}                          </p>
Copy after login

Why does $qp always equal $qp2? Because the find() function does all of its data gathering and then returns the QueryPath object.

This might seem esoteric, but it all has a very practical rationale. With this sort of interface, we can chain lots of methods together:

(你可以向使用 jQuery 一样来连缀方法)

                      <p class="sycode">                          <pre class="sycode" name="code">                              <p class="sycode">                                  qp(QueryPath        ::        HTML_STUB)        ->        find(        '        body        '        )        ->        text(        '        Hello World        '        )        ->        writeHTML();                              </p>
Copy after login

In this example, we have four method calls:

qp(QueryPath::HTML_STUB): Create a new QueryPath object and provide it with a stub of an HTML document. This returns the QueryPath object. find('body'): This searches the QueryPath document looking for an element named 'body'. That element is, of course, the portion of the HTML document. When it finds the body element, it keeps an internal pointer to that element, and it returns the QueryPath object (which is now wrapping the body element). text('Hello World'): This function takes the current element(s) wrapped by QueryPath and adds the text Hello World. As you have probably guessed, it, too, returns a QueryPath object. The object will still be pointing to the body element. writeHTML(): The writeHTML() function prints out the entire document. This is used to send the HTML back to the client. You'll never guess what this function returns. Okay, you guessed it. QueryPath.

So at the end of the chain above, we would have created a document that looks something like this:

                          <p class="sycode">                              <!       DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"       >              <       html        xmlns       ="http://www.w3.org/1999/xhtml"       >               <       head       >               <       meta        http-equiv       ="Content-Type"        content       ="text/html; charset=utf-8"       ></       meta       >               <       title       >       Untitled       </       title       >               </       head       >               <       body       >       Hello World       </       body       >              </       html       >                          </p>
Copy after login

Most of that HTML comes from the QueryPath::HTML_STUB. All we did was add the Hello World text inside of the tags.

Not all QueryPath functions return QueryPath objects. Some tools need to return other data. But those functions are well-documented in the included documentation.

These are the basic principles behind QueryPath. Now let's take a look at a larger example that exercises more of the QueryPath API.

A Longer Example

This example illustrates various core features of QueryPath.

In this example, we use some of the standard QueryPath functions (most of them implementing the jQuery interface) to build a new web page from scratch.

Each line of the code has been commented individually. The output from this is shown in a separate block beneath.

                          <p class="sycode">                              <?       php       /*       * * Using QueryPath. * * This file contains an example of how QueryPath can be used * to generate web pages. * @package QueryPath * @subpackage Examples * @author M Butcher <matt@aleph-null.tv> * @license LGPL The GNU Lesser GPL (LGPL) or an MIT-like license.        */              //        Require the QueryPath core.               require_once               '       QueryPath/QueryPath.php       '       ;       //        Begin with an HTML stub document (XHTML, actually), and navigate to the title.              qp(QueryPath       ::       HTML_STUB       ,               '       title       '       )        //        Add some text to the title                      ->       text(       '       Example of QueryPath.       '       )        //        Now look for the <body> element                      ->       find(       '       :root body       '       )        //        Inside the body, add a title and paragraph.                      ->       append(       '       <h1 id="This-is-a-test-page">This is a test page</h1><p>Test text</p>       '       )        //        Now we select the paragraph we just created inside the body                      ->       children(       '       p       '       )        //        Add a 'class="some-class"' attribute to the paragraph                      ->       attr(       '       class       '       ,               '       some-class       '       )        //        And add a style attribute, too, setting the background color.                      ->       css(       '       background-color       '       ,               '       #eee       '       )        //        Now go back to the paragraph again                      ->       parent()        //        Before the paragraph and the title, add an empty table.                      ->       prepend(       '       <table id="my-table"></table>       '       )        //        Now let's go to the table...                      ->       find(       '       #my-table       '       )        //        Add a couple of empty rows                      ->       append(       '       <tr></tr><tr></tr>       '       )        //        select the rows (both at once)                      ->       children()        //        Add a CSS class to both rows                      ->       addClass(       '       table-row       '       )        //        Now just get the first row (at position 0)                      ->       eq(       0       )        //        Add a table header in the first row                      ->       append(       '       <th>This is the header</th>       '       )        //        Now go to the next row                      ->       next       ()        //        Add some data to this row                      ->       append(       '       <td>This is the data</td>       '       )        //        Write it all out as HTML                      ->       writeHTML();       ?>                          </p>
Copy after login

The code above produces the following HTML:

代码

                              <p class="sycode">                                  <!        DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"        >                <        html         xmlns        ="http://www.w3.org/1999/xhtml"        >                 <        head        >                 <        meta         http-equiv        ="Content-Type"         content        ="text/html; charset=utf-8"        ></        meta        >                 <        title        >        Example of QueryPath.        </        title        >                 </        head        >                 <        body        >                 <        table         id        ="my-table"        >                 <        tr         class        ="table-row"        ><        th        >        This is the header        </        th        ></        tr        >                 <        tr         class        ="table-row"        ><        td        >        This is the data        </        td        ></        tr        >                 </        table        >                 <        h1        >        This is a test page        </        h1        >                 <        p         class        ="some-class"         style        ="background-color: #eee"        >        Test text        </        p        ></        body        >                 </        html        >                              </p>
Copy after login

Now you should have an idea of how QueryPath works. Grab a copy of the library and try it out! Along with the source code, you will get a nice bundle of HTML files that cover every single public function in the QueryPath library (no kidding). There are more examples there, too.

不错的东东!赶紧 Grab 它吧~~!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles