Core PHP

Creating a Simple XML Document

The program below demonstrates how to make an XML document using Simple XML. First, we call xmlwriter_open_memory() to initialize the XML memory. Next, we call xmlwriter_set_indent() to set the indent spacing for display. Then we set the string used for indenting the document by calling xmlwriter_set_indent_string(). Finally, a call to xmlwriter_start_document() sets the header type for the XML document.

The first and main element for our document is called trinity and has an attribute called name with the value God. Inside this element, we create three person elements, each of which has a name attribute with the values Father, Son, and Holy Spirit, respectively. This represents the doctrine that God is a trinity of three persons in one being. Those persons are God the Father, God the Son, and God the Holy Spirit.

At the end, we make a few function calls to finish the document. The call to xmlwriter_end_document() ends the documment. Calling xmlwriter_output_memory() gets the output string in a variable. Calling header() sets the header for the whole document that is generated by the web server. Finally, echo is used to output the document that was generated previously.

CreateSimpleXmlDoc.php

<?php

$qXmlWriter = xmlwriter_open_memory();
xmlwriter_set_indent($qXmlWriter, 1);
$res = xmlwriter_set_indent_string($qXmlWriter, ' ');

xmlwriter_start_document($qXmlWriter, '1.0', 'UTF-8');

// The first element: trinity
xmlwriter_start_element($qXmlWriter, 'trinity');

// Attribute 'name' for element 'trinity'
xmlwriter_start_attribute($qXmlWriter, 'name');
xmlwriter_text($qXmlWriter, 'God');
xmlwriter_end_attribute($qXmlWriter);

xmlwriter_start_element($qXmlWriter, 'person');
xmlwriter_start_attribute($qXmlWriter, 'name');
xmlwriter_text($qXmlWriter, 'Father');
xmlwriter_end_attribute($qXmlWriter);
xmlwriter_end_element($qXmlWriter); // person

xmlwriter_start_element($qXmlWriter, 'person');
xmlwriter_start_attribute($qXmlWriter, 'name');
xmlwriter_text($qXmlWriter, 'Son');
xmlwriter_end_attribute($qXmlWriter);
xmlwriter_end_element($qXmlWriter); // person

xmlwriter_start_element($qXmlWriter, 'person');
xmlwriter_start_attribute($qXmlWriter, 'name');
xmlwriter_text($qXmlWriter, 'Holy Spirit');
xmlwriter_end_attribute($qXmlWriter);
xmlwriter_end_element($qXmlWriter); // person

xmlwriter_end_element($qXmlWriter); // trinity


xmlwriter_end_document($qXmlWriter);

$sDoc = xmlwriter_output_memory($qXmlWriter);
header("Content-type: text/xml");
echo $sDoc;

?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.