Home >Backend Development >PHP Tutorial >phpmaster | Server-Side HTML Handling Using phpQuery
phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library.This is the definition given on the official phpQuery project page. If you have used jQuery, then you will have an idea of how it can simplify many tasks requiring DOM manipulation. phpQuery provides exactly the same functionalities to be used inside your server-side PHP code. You can say good bye to untidy HTML code generation using echo statements and similar methods. You will have access to most of the functionality provided by jQuery in phpQuery, which can broadly be divided into the 4 tasks mentioned below:
<span><span><?php </span></span><span><span>require("phpQuery/phpQuery.php"); </span></span><span><span>$doc = phpQuery<span>::</span>newDocument("<div/>");</span></span>The above code will create a basic HTML document with a div tag. The library provides various methods of creating documents; I have used the simplest one, but you can find others in demo.php and the documentation. Now we need to create an unordered list and add it to our HTML document.
<span><span><?php </span></span><span><span>... </span></span><span><span>$doc["div"]->append("<ul><li>Product Name</li><li>Price</li></ul>"); </span></span><span><span>$products = array( </span></span><span> <span>array("Product 1","<span><span></span>"</span>), </span></span><span> <span>array("Product 2","<span><span></span>"</span>), </span></span><span> <span>array("Product 3","<span><span></span>"</span>)); </span></span><span> </span><span><span>foreach($products as $key=>$product) { </span></span><span> <span>$doc["div ul"]->append("<li><span><span>$product[0]</span></li><li><span>$product[1]</span></li>"</span>); </span></span><span><span>} </span></span><span><span>print $doc;</span></span>You can see that we have the unordered list now. But all the elements are in a single column, which is the default. We have to move the even elements of the list into a second column.
<span><span><?php </span></span><span><span>... </span></span><span><span>$doc["div ul"]->attr("style", "width:420px;"); </span></span><span><span>$doc["div ul"]->find("li:even")->attr("style","width:200px; float:left; padding:5px; list-style:none;"); </span></span><span><span>$doc["div ul"]->find("li:odd")->attr("style","width:200px; float:left; padding:5px; list-style:none;");</span></span>I’m using the style attribute to define the CSS styles required for our example here, but it’s not recommended to use inline styles unless it’s really needed. Always use CSS classes to add styles. Now, let’s highlight the header and even numbered rows using phpQuery methods.
<span><span><?php </span></span><span><span>... </span></span><span><span>$doc["div ul"]->find("li:nth-child(4n)")->attr("style","background:#EEE; width:200px; float:left; padding:5px; list-style:none;"); </span></span><span><span>$doc["div ul"]->find("li:nth-child(4n-1)")->attr("style","background:#EEE; width:200px; float:left; padding:5px; list-style:none;"); </span></span><span><span>$doc["div ul"]->find("li:lt(1)")->attr("style","background:#CFCFCF; width:200px; float:left; padding:5px; list-style:none;");</span></span>We have completed our simple example, and you should now have an idea of how phpQuery can be used to simplify HTML generation server-side. Everything we did is almost the same as would be done with jQuery, except we did all the actions against the $doc object.
<span><span><?php </span></span><span><span>require("phpQuery/phpQuery.php"); </span></span><span><span>$doc = phpQuery<span>::</span>newDocument("<div/>");</span></span>Now let’s do it using phpQuery and compare the code and advantages.
<span><span><?php </span></span><span><span>... </span></span><span><span>$doc["div"]->append("<ul><li>Product Name</li><li>Price</li></ul>"); </span></span><span><span>$products = array( </span></span><span> <span>array("Product 1","<span><span></span>"</span>), </span></span><span> <span>array("Product 2","<span><span></span>"</span>), </span></span><span> <span>array("Product 3","<span><span></span>"</span>)); </span></span><span> </span><span><span>foreach($products as $key=>$product) { </span></span><span> <span>$doc["div ul"]->append("<li><span><span>$product[0]</span></li><li><span>$product[1]</span></li>"</span>); </span></span><span><span>} </span></span><span><span>print $doc;</span></span>phpQuery is easy if you have the knowledge of working with jQuery already. Most of the above code will be self-explanatory. I want to mention though that pq() refers to the current document. All the others are jQuery functions. And even though both look similar, the code which uses phpQuery provides better quality and extendibility. Think how brittle the original code can be if you have to add extra functionality later. Let’s assume we want to add additional validation on marks based on the working experience. In that scenario you’d have to add another method and assign the returned result inside the foreach loop. That means you have to change already written code, violating the Open-Closed Principle:
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.With the second example which uses phpQuery, the code is first generated without any validation, and then we pass the table into each function and the changes are placed into the original table. Each function does not affect the other functions, so we can write a new function for any new requirements and use it outside the loop with the other functions. We don’t modify already existing code, which sounds good, right? This is called decoration:
Decorator pattern is a design pattern that allows behavior to be added to an existing object dynamically.
phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library. It is written in PHP5 and provides an easy way to handle HTML elements on the server side. It allows developers to perform tasks such as HTML document traversal and manipulation, event handling, and animation, which were traditionally done on the client side. This can significantly improve the performance and security of web applications.
phpQuery stands out for its simplicity and ease of use, especially for developers already familiar with jQuery. It supports most of the jQuery syntax, making it easy to select, manipulate, and traverse HTML elements. Unlike some other libraries, phpQuery is chainable, meaning you can link together multiple actions in a single statement.
phpQuery can be installed using Composer, a dependency management tool for PHP. You can add phpQuery to your project by running the command composer require phpquery/phpquery. This will download and install the latest stable version of phpQuery and its dependencies.
phpQuery uses CSS3 selectors to select elements, similar to jQuery. For example, to select all paragraphs in a document, you would use $doc['p']. You can also use more complex selectors, such as $doc['div.content > p'] to select all paragraphs that are direct children of a div with the class “content”.
phpQuery provides several methods for manipulating elements. For example, you can use the append(), prepend(), after(), and before() methods to insert content. You can also use the attr() method to get or set the value of an attribute, and the addClass(), removeClass(), and toggleClass() methods to manipulate classes.
phpQuery supports event handling through the bind() method. You can use this method to attach event handlers to elements. For example, $doc['p']->bind('click', function() { echo 'Paragraph clicked!'; }); would echo “Paragraph clicked!” whenever a paragraph is clicked.
Yes, phpQuery supports AJAX through the ajax() method. This method allows you to send asynchronous HTTP requests to the server and manipulate the response using phpQuery.
phpQuery supports animations through the animate() method. This method allows you to create custom animations by changing CSS properties over time.
phpQuery provides several methods for traversing the DOM, such as children(), parent(), next(), prev(), find(), and closest(). These methods allow you to navigate through the elements in a document.
Yes, phpQuery can be used alongside other PHP libraries. It is designed to be flexible and interoperable, making it a great tool for any PHP developer’s toolkit.
The above is the detailed content of phpmaster | Server-Side HTML Handling Using phpQuery. For more information, please follow other related articles on the PHP Chinese website!