Build New HTML Documents

This section provides a tutorial example on how to create an HTML document using methods provided from the DOM extension.

DOMDocument objects can also be created from scratch instead of parsing an HTML document text string. This can be easily done by using the following methods:

The following program shows how to create a simple HTML document with these methods:

<?php
#  Create-HTML-DOM-Document.php
#- Copyright 2009 (c) HerongYang.com. All Rights Reserved.

  $file = $argv[1];

  $doc = new DOMDocument();
  createHTML($doc);
  $html = $doc->saveHTML();
  file_put_contents($file, $html);

function createHTML($doc) {

  $doc->appendChild($html);

  $body = $doc->createElement("body");
  $html->appendChild($body);

  $p = $doc->createElement("p");
  $body->appendChild($p);

  $text = $doc->createTextNode("Hello World!");
  $p->appendChild($text);

  $body->setAttribute("bgcolor", "#ddddff");
}
?>

Now run the PHP script. You should get a simple HTML document as shown below.

herong> php Create-HTML-DOM-Document.php Hello.html

herong> type Hello.html
<html><body bgcolor="#ddddff"><p>Hello World!</p></body></html>

Table of Contents

 About This Book

 Introduction and Installation of PHP

 Managing PHP Engine and Modules on macOS

 Managing PHP Engine and Modules on CentOS

 cURL Module - Client for URL

DOM Module - Parsing HTML Documents

 DOM (Document Object Model) Module

 Parse and Traverse HTML Documents

Build New HTML Documents

 Load HTML Documents with LIBXML_NOBLANKS

 Remove Whitespaces in HTML Documents

 DOCTYPE Element in HTML Documents

 Remove Dummy Elements in HTML Documents

 Install DOM Extension on CentOS

 GD Module - Manipulating Images and Pictures

 MySQLi Module - Accessing MySQL Server

 OpenSSL Module - Cryptography and SSL/TLS Toolkit

 PCRE Module - Perl Compatible Regular Expressions

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

 Zip Module - Managing ZIP Archive Files

 References

 Full Version in PDF/EPUB