This section contains the detail about the example of XML File Creation in PHP.
PHP-XML File Creation Example:
XML was designed to transport and store data. In this example you can see how to create a xml file using PHP.
First we will create a DOMDocument object. new DOMDocument("String version") object represents an entire HTML or XML document, serves as the root of the document tree. The document object model document provides many functions to generate xml file. We will use some function like:
createElement("String") : used to create new element in xml file generation.
appendChild("child name") : append the particular child in the root element.
createTextNode("text") : used to create a text node in the xml document.
save('xmlfilename.xml') : used to save the generated file in the particular location.
saveXML() : used to save as xml file.
Example :
<?php $DOMObject = new DOMDocument("1.0"); header("Content-Type: text/plain"); $root_element = $DOMObject->createElement("root"); $DOMObject->appendChild($root_element); $root_item1 = $DOMObject->createElement("child1"); $root_element->appendChild($root_item1); $root_item_text1 = $DOMObject->createTextNode("clied1 text"); $root_item1->appendChild($root_item_text1); $root_item2 = $DOMObject->createElement("child2"); $root_element->appendChild($root_item2); $root_item_text2 = $DOMObject->createTextNode("clied2 text"); $root_item2->appendChild($root_item_text2); $DOMObject->save('root.xml'); echo $DOMObject->saveXML(); ?>
This tutorial provide the basic functioning for xml file creation. After run this example the browser output is:
Browser Output :
<?xml version="1.0"?> <root> <child1>clied1 text</child1> <child2>clied2 text</child2> </root>
And root.xml file generated in the location where you want to save this file.
[ 0 ] Comments