oxsimplexml.php

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