Skip to content

Action helper that converts SQL result to XML

2010 September 6
by Richard Knop

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:

  1. <?php
  2. class My_Controller_Action_Helper_SqlToXml extends Zend_Controller_Action_Helper_Abstract
  3. {
  4.     public function direct($sqlResult, $rootElementName, $childElementName, $singleRow, $encoding = 'UTF-8')
  5.     {
  6.         // create XML documnt      
  7.         $doc = new DomDocument('1.0', $encoding);
  8.        
  9.         // insert a root element
  10.         $root = $doc->createElement($rootElementName);
  11.         $root = $doc->appendChild($root);
  12.        
  13.         // if the SQL result set contains only a singler row
  14.         if (true === $singleRow) {
  15.             $xmlData .= $this->rowToXml($doc, $root, $sqlResult, $childElementName);
  16.         }
  17.         // if the SQL result set is an object array
  18.         else if (false === $singleRow) {
  19.             foreach ($sqlResult as $row) {
  20.                 $xmlData .= $this->rowToXml($doc, $root, $row, $childElementName);
  21.             }
  22.         }
  23.        
  24.         // return XML string
  25.         return $doc->saveXML();
  26.     }
  27.    
  28.     private function rowToXml($doc, $root, $row, $childElementName)
  29.     {
  30.         // insert a child element
  31.         $occ = $doc->createElement($childElementName);
  32.           $occ = $root->appendChild($occ);        
  33.          
  34.           // iterate through each public object property and insert a shild element
  35.         foreach ($row as $property => $value) {
  36.             $child = $doc->createElement($property);
  37.             $child = $occ->appendChild($child);
  38.            
  39.             $childValue = $doc->createTextNode($value);
  40.             $childValue = $child->appendChild($childValue);
  41.         }
  42.     }
  43. }

Hope some of you will find it useful.

2 Responses leave one →
  1. March 14, 2011

    Hi! I’ve created one that’s a little bit more abstract. Just pass an array to it’s direct() :)

    http://pastebin.com/89sXAM5m

Trackbacks and Pingbacks

  1. Zend Framework News » Blog Archive » Action Helper für Konvertierung von SQL Ergebnissen nach XML

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS