HomePHP Page 2 - Handling HTML Strings and Files with the DOM XML Extension in PHP 5
Loading HTML code from a specific string with the loadHTML() method - PHP
The DOM XML extension has a few additional methods that can be used to process HTML files and strings, at least at a pretty basic level. Thus, this fifth part of the series will be entirely focused on explaining how to work with these methods. I will include some illustrative code samples.
In consonance with the concepts that I deployed in the introduction, the DOM XML extension includes some useful methods aimed specifically at handling HTML in different ways. To demonstrate this specific capacity of the library I’m going to teach you how to utilize the brand new “loadHTML()” method, which comes in handy when loading an HTML string onto the web server’s memory.
That being said, here’s an example that illustrates how the aforementioned method does its thing:
// example on loading HTML from an existing string using the 'loadHTML()' method
$html='<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content- Type" content="text/html; charset=iso-8859-1" /><title>Example of loading HTML</title></head><body><p>Example on loading HTML</p></body></html>';
/* displays the following
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
As demonstrated by the above code sample, the “loadHTML()” method is convenient for loading an HTML string into a PHP object. In this particular case, the method in question is first used to retrieve some simple HTML content, which is then echoed to the browser. Not too hard to understand, right?
So far, so good. With the introduction of the previous hands-on example, hopefully you’ve already grasped how the pertinent “loadHTML()” method does its business. However, the DOM XML extension still has some other helpful methods that can be used to handle HTML. Thus, since you may want to learn how to put them to work for you, in the upcoming section I’ll be teaching you a brand new method, named “loadHTMLFile(), which can be used to read the contents of a specified HTML file.
To learn the full details of how to use this handy method, please click on the link that appears below and keep reading.