As I mentioned in the section that you just read, the last example that I’m going to teach you in this article will be specifically aimed at demonstrating how to build a basic HTML file from its corresponding DOM representation. Surely, at this very moment, you’re wondering how this process can be performed. The answer to that question is via the brand new “saveHTMLFile()” method.
In order to help you grasp how this method functions, below I coded another illustrative example that shows how to create a primitive HTML document via the DOM API and then save it to a specified file destination.
Here’s the corresponding code sample. Please take a close look at it:
// example on building an HTML document from the DOM representation using the saveHTMLFile()' method
// format output
// create <html> element
// create <head> element
// create <title> element
// create text for title of HTML page
$text=$dom->createTextNode('This title was created with the DOM XML extension of PHP');
// save HTML to file
echo 'The file just created has a size of '. $dom->saveHTMLFile('test_file.htm'). ' bytes.';
/* displays the following
The file just created has a size of 168 bytes
As shown in the previous example, a trivial HTML document is built by using some of the methods that you learned so far, such as “createElement()” and “appendChild()” respectively. Then, once the document in question has been created, it’s simply saved to a target file, called “test_file.htm”, by calling the pertinent “saveHTMLFile()” method.
While the functionality of “saveHTMLFile()” is pretty easy to grasp, you should notice two important things. First, I used the brand new property, called “formatOutput”, to adequately format the contents of the file that is just about to be created. And second, if the mentioned file doesn’t exist, then the “saveHTMLFile()” method will attempt to build it. Simple and short!
Lastly, before I forget, here’s the signature of the sample HTML file constructed with “saveHTMLFile()”:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>This title was created with the DOM XML extension of PHP</title>
As usual with my articles on PHP development, you’re free to tweak all of the code samples developed earlier so you can improve your skills using the DOM XML PHP extension.
In this fifth chapter of the series, you learned how to handle HTML strings and files through the set of methods provided by the DOM XML extension. Since they’re quite simple to use, you shouldn’t have major difficulties incorporating them into your own PHP applications.
In the upcoming part, I’ll be exploring the solid capabilities of the DOM XML library when it comes to parsing parent and child nodes of a specified XML document, so you don’t have any excuses to miss it!
blog comments powered by Disqus