Write an XML File


// version and encoding;
$dom = new DomDocument("1.0", "ISO-8859-1");

// we create a XML Node 
$usersElem = $dom->createElement('users');

// Select all the rows in the names table
$query = "SELECT * FROM names";
$result = mysql_query($query);

if (!$result) {
die('Invalid query: ' . mysql_error());
// Loop through the rows, adding XML nodes
while ($row = @mysql_fetch_assoc($result)){

$usersElem->appendChild ( $dom->createElement('firstname', $row['firstname']) );
$usersElem->appendChild ( $dom->createElement('lastname', $row['lastname']) );
$usersElem->appendChild ( $dom->createElement('password', $row['password']) );
// add $usersElem to dom
$dom->appendChild( $usersElem );

// $dom has entire XML
$dom->formatOutput = true; // this adds spaces, new lines 
// save it as XML
$xmlSave = $dom->save('users.xml'); // returns true/false upon failure or success

if($xmlSave == false)
echo " Sorry you had a problem! ";
echo " File created! " . "<br>";


<title> Demo : Write XML File </title>
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8
{ list-style-type: decimal !important }
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
<pre class="prettyprint linenums">
<code class="language-xml"><?php echo htmlspecialchars(file_get_contents("users.xml"), ENT_QUOTES); ?></code>

This is basic example of writing an XML file in php. You can pretty it up with prettify.js.

Leave a Reply

Your email address will not be published. Required fields are marked *