Use phpQuery for server-side HTML processing

Source: Internet
Author: User
In our daily Daily web development tasks, it is necessary for us to work with client and server code. We will write the PHP business logic and generate the HTML to be displayed in the user's browser. Then, we use a framework such as jQuery or prototype to provide client interaction.

In our daily Daily web development tasks, it is necessary for us to work with client and server code. We will write the PHP business logic and generate the HTML to be displayed in the user's browser. Then, we use a framework such as jQuery or prototype to provide client interaction.

Now think about how you can use the PHP code on the server to change and operate the HTML generated. PhpQuery is the final solution that will come to your mind. If you have not heard of phpQuery, you may be interested in this article because I want to give you a brief introduction to phpQuery and explain how to use it in actual projects.

What is phpQuery?

PhpQuery is a file Object Model (DOM) API driven by CSS3 selector, which is based on the jQuery JavaScript library server.

This is the official phpQuery project definition page. If you have already used jQuery, you will have the idea of how to simplify DOM operations and multi-task operations. PhpQuery exactly provides the same functions used in your server-side PHP code. You can use echo statements and similar methods to say goodbye to messy HTML code generation.

You will have the opportunity to obtain the jQuery functions provided by most of the four tasks mentioned below in phpQuery:

  • Create DOM elements
  • Select and operate elements
  • Traverse through DOM
  • Print the output to the browser

For the "transplanted jQuery section", you can use the function that is called the task executed by the function provided by phpQuery to see the first feature:

  • Select-find the element based on the given condition.
  • Attribute-operate the attributes of the DOM element.
  • Traversal-List of elements selected for a business trip.
  • Operation-add and delete selected elements.
  • Ajax-create a server-side Ajax request.
  • Activity-bind a DOM event to the selected element.
  • Utility-common functions to support other functions.

You can download the phpQuery Library code.google.com/P/phpquery from the project page. Copy the folder to your web server. The installation is simple. you can run the demo. php file to get started.

How to use phpQuery

I will show you how to create an unordered list of two columns. the titles and colors of different rows are odd and even, as shown in the image:

First, let's create an HTML document using phpQuery:

123

The above code creates a basic HTML document with a div tag. This library provides various methods to create documents. I use the simplest one, but you can find other people in demo. php and documentation.

Now, we need to create an unordered list and add it to our HTML file.

123456789101112 Append ("
  • Product Name
  • Price
"); $ Products = array (" Product 1 "," $30 "), array (" Product 2 "," $50 "), array ("Product 3", "$20"); foreach ($ productsas $ key => $ product) {$ doc ["div ul"]-> append ("
  • $ Product [0]
  • $ Product [1]
  • ");} Print $ doc;

    As you can see, we have an unordered list now. However, all elements are in a single column, which is default. We need to move the even number element of the list to the second column.

    12345 Attr ("style", "width: 420px;"); $ doc ["div ul"]-> find ("li: even")-> attr ("style ", "width: 200px; float: left; padding: 5px; list-style: none;"); $ doc ["div ul"]-> find ("li: odd ") -> attr ("style", "width: 200px; float: left; padding: 5px; list-style: none ;");

    The style attribute I used is defined here as the CSS style required for our example, but it is not recommended to use inline style unless it is actually needed. Always use the CSS class to add styles.

    Now, let's highlight the title and use the phpQuery method to display even rows.

    12345 Find ("li: nth-child (4n)")-> attr ("style", "background: # EEE; width: 200px; float: left; padding: 5px; list-style: none; "); $ doc [" div ul "]-> find (" li: nth-child (4n-1) ")-> attr (" style ", "background: # EEE; width: 200px; float: left; padding: 5px; list-style: none ;"); $ doc ["div ul"]-> find ("li: lt (1)")-> attr ("style", "background: # CFCFCF; width: 200px; float: left; padding: 5px; list-style: none ;");

    We have completed our simple example. now you should have an idea on how phpQuery can be used to simplify HTML generation on the server side. Almost everything we do will be done using jQuery, except for all the actions we have done $ doc object.

    Importance of phpQuery

    Although I explain the phpQuery function, you must know why we have a client for jQuery when we need a library. I will demonstrate the importance of phpQuery in actual use cases.

    Consider the following situation: Suppose we have an information table about who to interview Web developers, as shown below.

    Now, we have a list of development requirements in this case:

    • Applicants who have obtained an exam sign greater than 60 should be highlighted in blue.
    • If the applicant has more than three years of work experience, the above link should be marked with "apply for senior software engineer" and the link "apply for software engineer" that other applicants should have ".
    • The company has an experienced salary structure:
      • 1 year-$5,000
      • 2 years-$10,000
      • 3 years-$20,000
      • More than 3 years-$50,000

      The salary column should emphasize who meets the conditions for Green applications.

    This is the output appearance:

    Developers can provide the following solutions to meet the requirements for using pure PHP code.

    1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 60 )? "Pass": "fail";} functionpositionLink ($ experience) {return ($ experience> 3 )? 'Apply for Senior Software engineer': 'Apply for Software engineer';} functionsalaryClass ($ experience, $ salary) {switch ($ experience) {case1: return ($ salary <5000 )? "Accept": "reject"; case2: return ($ salary <10000 )? "Accept": "reject"; case3: return ($ salary <20000 )? "Accept": "reject"; default: return ($ salary <50000 )? "Accept": "reject ";}}

    Now, let's use phpQuery to compare code and advantages.

    123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 Append ('name Marks Experience Position Expected Salary '); foreach ($ applicantsas $ key => $ applicant) {$ doc ["# main"]-> append (''); foreach ($ applicantas $ field => $ info) {$ doc ["# main"]-> find ("# app _". $ key)-> append (''. $ info. ""); if ($ field = "experience") {$ doc ["# main"]-> find ("# app _". $ key)-> append ('-') ;}} addMarksClass ($ doc); addSalaryClass ($ doc); addPositionLink ($ doc); print $ doc; functionaddMarksClass (& $ d Oc) {$ marks = pq (". _ marks "); foreach ($ marksas $ appMark) {if (pq ($ appMark)-> html ()> 60) {pq ($ appMark) -> addClass ("pass");} else {pq ($ appMark)-> addClass ("fail") ;}} functionaddSalaryClass (& $ doc) {$ marks = pq (". _ salary "); foreach ($ marksas $ appMark) {$ experience = pq ($ appMark)-> parent ()-> find (". _ experience ")-> html (); $ salary = pq ($ appMark)-> html (); switch ($ experience) {case1: pq ($ appMark) -> addClass (($ Salary <5000 )? "Accept": "reject"); break; case2: pq ($ appMark)-> addClass ($ salary <10000 )? "Accept": "reject"); break; case3: pq ($ appMark)-> addClass ($ salary <20000 )? "Accept": "reject"); break; default:

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.