Combining XmlWriter objects?
- by Kevin
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).