View Full Version : Outputting XML with PHP: DOM or non_DOM?

03-01-2009, 07:27 PM
Does anyone know is there a difference or a reason why to use a dom parent/child approach to writing an xml file from php as opposed to just writing the full set of nested tag? Is there a difference in the usability of the output file?

Here is a snippet of an example of what I mean by non-dom xml output and under it is a snippet of an example of what I mean by dom output. This question has relevance mostly because I am using a php 4 server where the nice functions for the dom approach are not available (or if there are some others, I cannot find them documented).

non-DOM approach:

echo "<?xml version=\"1.0\" ?>\n";
echo "<gallery>\n";
echo "<Images>$numLogos</Images>\n";
echo "<Image>\n";
for($i=1 ; $i <= $numLogos ; $i++)
echo "<ImagePath$i>$directory".$filearray[$i]."</ImagePath$i>\n";
echo "</Image>\n";
echo "</gallery>\n";

DOM approach

$doc = new DomDocument("1.0", "utf-8");
$node = $doc->createElement("gallery");
$parnode = $doc->appendChild($node);
$node = $doc->createElement("settings");
$settingsNode = $parnode->appendChild($node);
$node = $doc->createElement("mediaFolder");
$mediaFolderLargeNode = $settingsNode->appendChild($node);
$mediaFolderLargeNode->setAttribute("type", "large");
$mediaFolderLargeNode->setAttribute("media", "image");
$mediaFolderLargeNode->nodeValue = "images/";


03-01-2009, 11:38 PM
DOM handles XML at the level of being XML, while the non-dom you have there is nothing but strings. DOM gives you a fine grain control of you're elements, attributes and data, while a string would need a custom parser to separate. DOM will let you create new elements and insert them into specific locations in you're dom tree, while this would be very difficult without.
That enough info?

03-02-2009, 12:42 AM
Thanks -- Sounds like DOM is the way to go, then. Is there a way to do it in php 4 and an example anywhere? I have looked, but not found it.


03-02-2009, 12:51 AM
I've never used this before, but I believe this is where the PHP dom all started: http://php.ca/manual/en/book.domxml.php
DOMXML is the PHP4 usage of the dom. I haven't gone through the methods or anything like that, but it does appear to be object oriented. You may want to consider making a wrapper for it to expose methods instead of directly manipulating the domxml. This will make a conversion to PHP5 domdocument much less painful.