oxsimplexml.php

Go to the documentation of this file.
00001 <?php
00002 
00006 class oxSimpleXml
00007 {
00016     protected function _addSimpleXmlElement($oXml, $oInput)
00017     {
00018         if (is_object( $oInput )) {
00019             $aObjectVars = get_object_vars( $oInput );
00020         } elseif (is_array($oInput) ) {
00021             $aObjectVars = $oInput;
00022         } else {
00023             return $oXml;
00024         }
00025 
00026         foreach ($aObjectVars as $sKey => $oVar) {
00027             if (is_object( $oVar ) ) {
00028                 $oChildNode = $oXml->addChild($sKey);
00029                 $this->_addSimpleXmlElement($oChildNode, $oVar);
00030             } elseif (is_array( $oVar) ) {
00031                 foreach ($oVar as $oSubValue) {
00032                     //this check for complex type is probably redundant, but I give up to solve it over single recursion call
00033                     //use existing Unit tests for refactoring
00034                     if (is_array($oSubValue) || is_object($oSubValue)) {
00035                         $oChildNode = $oXml->addChild($sKey);
00036                         $this->_addSimpleXmlElement($oChildNode, $oSubValue);
00037                     } else {
00038                         $oXml->addChild($sKey, $oSubValue);
00039                     }
00040                 }
00041             } else {
00042                 //assume $oVar is string
00043                 $oXml->addChild($sKey, $oVar);
00044             }
00045         }
00046 
00047         return $oXml;
00048     }
00049 
00076     public function objectToXml($oInput, $sDocument)
00077     {
00078         $oXml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><$sDocument/>");
00079         $this->_addSimpleXmlElement($oXml, $oInput);
00080 
00081         return $oXml->asXml();
00082     }
00083 
00091     public function xmlToObject($sXml)
00092     {
00093         return simplexml_load_string($sXml);
00094     }
00095 }