Combining XmlWriter objects?

Posted by Kevin on Stack Overflow See other posts from Stack Overflow or by Kevin
Published on 2009-11-29T23:33:21Z Indexed on 2010/06/16 12:52 UTC
Read the original article Hit count: 234

Filed under:
|
|

The way my application is structured, each component generates output as XML and returns an XmlWriter object. Before rendering the final output to the page, I combine all XML and perform an XSL transformation on that object. Below, is a simplified code sample of the application structure.

Does it make sense to combine XmlWriter objects like this? Is there a better way to structure my application? The optimal solution would be one where I didn't have to pass a single XmlWriter instance as a parameter to each component.

function page1Xml() {
 $content = new XmlWriter();
 $content->openMemory();
 $content->startElement('content');
 $content->text('Sample content');
 $content->endElement();
 return $content;
}

function generateSiteMap() {
 $sitemap = new XmlWriter();
 $sitemap->openMemory();
 $sitemap->startElement('sitemap');
 $sitemap->startElement('page');
 $sitemap->writeAttribute('href', 'page1.php');
 $sitemap->text('Page 1');
 $sitemap->endElement();
 $sitemap->endElement();
 return $sitemap;
}

function output($content)
{
 $doc = new XmlWriter();
 $doc->openMemory();
 $doc->writePi('xml-stylesheet', 'type="text/xsl" href="template.xsl"'); 
 $doc->startElement('document');

 $doc->writeRaw( generateSiteMap()->outputMemory() );
 $doc->writeRaw( $content->outputMemory() );

 $doc->endElement();
 $doc->endDocument();

 $output = xslTransform($doc);
 return $output;
}

$content = page1Xml();
echo output($content);


Update:
I may abandon XmlWriter altogether and use DomDocument instead. It is more flexible and it also seemed to perform better (at least on the crude tests I created).

© Stack Overflow or respective owner

Related posts about php

Related posts about xmlwriter