oxsimplexml.php

Go to the documentation of this file.
00001 <?php
00002 
00024 class oxSimpleXml
00025 {
00026 
00035     public function objectToXml($oInput, $sDocument)
00036     {
00037         $oXml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><$sDocument/>");
00038         $this->_addSimpleXmlElement($oXml, $oInput);
00039 
00040         return $oXml->asXml();
00041     }
00042 
00050     public function xmlToObject($sXml)
00051     {
00052         return simplexml_load_string($sXml);
00053     }
00054 
00064     protected function _addSimpleXmlElement($oXml, $oInput, $sPreferredKey = null)
00065     {
00066         $aElements = is_object($oInput) ? get_object_vars($oInput) : (array) $oInput;
00067 
00068         foreach ($aElements as $sKey => $mElement) {
00069             $oXml = $this->_addChildNode($oXml, $sKey, $mElement, $sPreferredKey);
00070         }
00071 
00072         return $oXml;
00073     }
00074 
00085     protected function _addChildNode($oXml, $sKey, $mElement, $sPreferredKey = null)
00086     {
00087         $aAttributes = array();
00088         if (is_array($mElement) && array_key_exists('attributes', $mElement) && is_array($mElement['attributes'])) {
00089             $aAttributes = $mElement['attributes'];
00090             $mElement = $mElement['value'];
00091         }
00092 
00093         if (is_object($mElement) || is_array($mElement)) {
00094             if (is_int(key($mElement))) {
00095                 $this->_addSimpleXmlElement($oXml, $mElement, $sKey);
00096             } else {
00097                 $oChildNode = $oXml->addChild($sPreferredKey? $sPreferredKey : $sKey);
00098                 $this->_addNodeAttributes($oChildNode, $aAttributes);
00099                 $this->_addSimpleXmlElement($oChildNode, $mElement);
00100             }
00101         } else {
00102             $oChildNode = $oXml->addChild($sPreferredKey? $sPreferredKey : $sKey, $mElement);
00103             $this->_addNodeAttributes($oChildNode, $aAttributes);
00104         }
00105 
00106         return $oXml;
00107     }
00108 
00117     protected function _addNodeAttributes($oNode, $aAttributes)
00118     {
00119         $aAttributes = (array) $aAttributes;
00120         foreach ($aAttributes as $sKey => $sValue) {
00121             $oNode->addAttribute($sKey, $sValue);
00122         }
00123 
00124         return $oNode;
00125     }
00126 }