Action helper that converts SQL result to XML
2010 September 6
Here is a simple Zend Framework controller action helper that converts SQL result to XML. The SQL result should be fetched as an object or an array of objects:
-
<?php
-
class My_Controller_Action_Helper_SqlToXml extends Zend_Controller_Action_Helper_Abstract
-
{
-
public function direct($sqlResult, $rootElementName, $childElementName, $singleRow, $encoding = 'UTF-8')
-
{
-
// create XML documnt
-
$doc = new DomDocument('1.0', $encoding);
-
-
// insert a root element
-
$root = $doc->createElement($rootElementName);
-
$root = $doc->appendChild($root);
-
-
// if the SQL result set contains only a singler row
-
if (true === $singleRow) {
-
$xmlData .= $this->rowToXml($doc, $root, $sqlResult, $childElementName);
-
}
-
// if the SQL result set is an object array
-
else if (false === $singleRow) {
-
foreach ($sqlResult as $row) {
-
$xmlData .= $this->rowToXml($doc, $root, $row, $childElementName);
-
}
-
}
-
-
// return XML string
-
return $doc->saveXML();
-
}
-
-
private function rowToXml($doc, $root, $row, $childElementName)
-
{
-
// insert a child element
-
$occ = $doc->createElement($childElementName);
-
$occ = $root->appendChild($occ);
-
-
// iterate through each public object property and insert a shild element
-
foreach ($row as $property => $value) {
-
$child = $doc->createElement($property);
-
$child = $occ->appendChild($child);
-
-
$childValue = $doc->createTextNode($value);
-
$childValue = $child->appendChild($childValue);
-
}
-
}
-
}
Hope some of you will find it useful.
2 Responses
leave one →
Hi! I’ve created one that’s a little bit more abstract. Just pass an array to it’s direct()
http://pastebin.com/89sXAM5m