Table Of Contents:

In this screencast you will be taught how to generate a simple XML file using PHP class DomDocument.

The XML Creation Screencast

http://blip.tv/file/get/Formatix-GenerationXmlDomdocumenteng886.flv

The XML Creation Source Code

<?php

/**********************************************************************/
/*  Description: Creating a XML file using DomDocument php class      */
/*                                                                    */
/*  Author: Christophe Fiat                                           */
/*  Web Site: http://www.formatix.eu                                  */
/**********************************************************************/

  // Get an instance of Domdocument
  $doc = new DOMDocument();

  // specify the version and encoding
  $doc->version = '1.0';
  $doc->encoding = 'ISO-8859-1';

  // Create a comment
  $comment_elt = $doc->createComment('Generated by FormatiX.Eu ');
  // Put this comment at the Root of the XML doc
  $doc->appendChild($comment_elt);

  // Create an Empty element 'note'
  $note_elt = $doc->createElement('note');
  // Put the 'note' element at the Root of the XML doc (just after the comment)
  $doc->appendChild($note_elt);

  // Create to/from/heading/body elements
  $to_elt      = $doc->createElement('to', 'Philippe');
  $from_elt    = $doc->createElement('from', 'Chris');
  $heading_elt = $doc->createElement('heading', 'Do not Forget');
  $body_elt    = $doc->createElement('body');

  // Specify that thos newly created elements are 'note' children
  $note_elt->appendChild($to_elt);
  $note_elt->appendChild($from_elt);
  $note_elt->appendChild($heading_elt);
  $note_elt->appendChild($body_elt);

  // Create a Cdata section
  $cdata_sect_elt = $doc->createCDATASection('It's my Birthday');
  // Put this section in 'body'
  $body_elt->appendChild($cdata_sect_elt);

  // Beautify
  $doc->formatOutput = true;

  // Display the XML content we just created
  echo $doc->saveXML();

  // Save this to simple_eng.xml
  $doc->save('simple_eng.xml');

  // That's All folks!

?>

Generated XML file


<?xml version="1.0" encoding="ISO-8859-1"?>
<!--Generated by FormatiX.Eu -->
<note>
  <to>Philippe</to>
  <from>Chris</from>
  <heading>Do not Forget</heading>
  <body><![CDATA[It's my Birthday]]></body>
</note>

Download the Archive

> Download < PHP script and XML result.