Sep 20, 2008

PHP: XML Generator - array to xml converter

I created this class for my Online Briscola project - which is a client-server application, the client application is a flash movie and the server runs on PHP sockets. They comunicate through XML commands, so this class is basicly an array-to-xml converter. It uses PHP's XMLWriter
<?
class xmlgen {

 var $xml;
 var $ver;
 var $charset;
 
 function xmlgen($ver='1.0',$charset='UTF-8') {
  $this->ver = $ver;
  $this->charset = $charset;
 }

 function generate($root,$data=array()) {
  $this->xml = new XmlWriter();
  $this->xml->openMemory();
  $this->xml->startDocument($this->ver,$this->charset);
  $this->xml->startElement($root);
  $this->write($this->xml, $data);
  $this->xml->endElement();
  $this->xml->endDocument();
  $xml = $this->xml->outputMemory(true);
  $this->xml->flush();
  return $xml;
 }
 
 function write(XMLWriter $xml, $data){
     foreach($data as $key => $value){
         if(is_array($value)){
             $xml->startElement($key);
             $this->write($xml,$value);
             $xml->endElement();
             continue;
         }
         $xml->writeElement($key,$value);
     }
 }
 
}
?>
When the object is constructed
$xmlgen = new xmlgen();
you can pass your array to the class' generate() function, for example
$array = array(
 "first_element"=>"element_value",
 "second_element"=>array(
  "second_element_value1"=>"value1_subvalue")
);

echo $xmlgen->generate('root',$array);
The output will be something simmilar to:
<?xml version="1.0" encoding="UTF-8"?>
<root>
 <first_element>
   element_value
 </first_element>
 <second_element>
  <second_element_value1>
      value1_subvalue
  </second_element_value1>
 </second_element>
</root>

2 comments:

Guilherme Pinto said...
This comment has been removed by the author.
Guilherme Pinto said...

Hi,
This forum is very old, but I make a upgrade in code, I needed create a XML with multiple nodes equal, is impossible in array. example:





Willian


Mike



The code:

function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
if(is_numeric($key)){
$this->write($xml,$value);
continue;
}else{
$xml->startElement($key);
$this->write($xml,$value);
$xml->endElement();
continue;
}
}
$xml->writeElement($key,$value);
}
}

Array:
([house]
[0]
[room]
owner=>Willian
,[1]
[room]
owner=Mike
)