rest-proxy.php

Simple proxy for RESTful APIs
git clone git://git.finwo.net/app/rest-proxy.php
Log | Files | Refs | README

XmlTransformer.php (2142B)


      1 <?php
      2 
      3 /**
      4  * See http://www.akchauhan.com/php-class-for-converting-xml-to-object-and-object-to-xml/
      5  */
      6 
      7 namespace Finwo\Framework;
      8 
      9 use XMLWriter;
     10 
     11 class XmlTransformer {
     12     private $xml;
     13 
     14     // Constructor
     15     public function __construct() {
     16         $this->xml = new XMLWriter();
     17         $this->xml->openMemory();
     18         $this->xml->startDocument('1.0');
     19         $this->xml->setIndent(true);
     20         $this->xml->setIndentString('    ');
     21     }
     22 
     23     // Method to convert Object into XML string
     24     public function objToXML($obj) {
     25 
     26         if(is_array($obj)) {
     27             $obj = json_decode(json_encode($obj));
     28         }
     29 
     30         $this->getObject2XML($this->xml, $obj);
     31 
     32         $this->xml->endElement();
     33 
     34         return $this->xml->outputMemory(true);
     35     }
     36 
     37     // Method to convert XML string into Object
     38     public function xmlToObj($xmlString) {
     39         return simplexml_load_string($xmlString);
     40     }
     41 
     42     private function getObject2XML(XMLWriter $xml, $data) {
     43         foreach($data as $key => $value) {
     44             if(is_object($value)) {
     45                 $xml->startElement($key);
     46                 $this->getObject2XML($xml, $value);
     47                 $xml->endElement();
     48                 continue;
     49             }
     50             else if(is_array($value)) {
     51                 $this->getArray2XML($xml, $key, $value);
     52             }
     53 
     54             if (is_string($value)) {
     55                 $xml->writeElement($key, $value);
     56             }
     57         }
     58     }
     59 
     60     private function getArray2XML(XMLWriter $xml, $keyParent, $data) {
     61         foreach($data as $key => $value) {
     62             if (is_string($value)) {
     63                 $xml->writeElement($keyParent, $value);
     64                 continue;
     65             }
     66 
     67             if (is_numeric($key)) {
     68                 $xml->startElement($keyParent);
     69             }
     70 
     71             if(is_object($value)) {
     72                 $this->getObject2XML($xml, $value);
     73             }
     74             else if(is_array($value)) {
     75                 $this->getArray2XML($xml, $key, $value);
     76                 continue;
     77             }
     78 
     79             if (is_numeric($key)) {
     80                 $xml->endElement();
     81             }
     82         }
     83     }
     84 }