Before and After: Creating New XML Documents

If you want to create a new XML document, you have two choices. Since XML is text, you can always print it yourself using print. The other option is to use DOM.

With DOM you assemble an entire XML document by calling methods in PHP. When you’re done, tell DOM to convert your DOM object into XML.

At first, it is much easier to create XML yourself and avoid DOM. Just as extracting information from a DOM object requires multiple steps, adding new nodes to a DOM tree isn’t easy. However, using DOM does have some benefits:

  • Your XML is always well-formed and without syntax errors.

  • DOM correctly outputs your document in any one of many different character encodings.

  • You can easily validate your object against a schema.

SimpleXML does not allow you to create XML documents.

Creating an Address Book

The code examples in this section create the address book from Example 5-1 and populate it with the first entry.

PHP 4 and DOM

Example 5-19 shows how to create an address book in PHP 4.

Example 5-19. Creating XML with PHP 4 and DOM

// create a new document $dom = domxml_new_doc('1.0'); $people = $dom->append_child($dom->create_element('address-book')); $person = $people->append_child($dom->create_element('person')); $person->set_attribute('id', 1); $person->append_child($dom->create_comment('Rasmus Lerdorf')); $e = $person->append_child($dom->create_element('firstname')); $e->append_child($dom->create_text_node('Rasmus')); $e = $person->append_child($dom->create_element('lastname')); ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.