note 79125 deleted from book.dom by cmb
| From: | cmb@php.net | Date: | Sun, 15 Sep 2019 18:12:05 +0000 |
| Subject: | note 79125 deleted from book.dom by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212231@lists.php.net to get a copy of this message | ||
Note Submitter: trollboy at shoggoth dot net
----
I wrote a simple class to turn an associative array into xml, as this seems like something fairly
simple, but nothing out there does it that I know of. That said, enjoy.
<?php
/**
* basic class for converting an array to xml.
* @author Matt Wiseman (trollboy at shoggoth.net)
*
*/
class array2xml {
public $data;
public $dom_tree;
/**
* basic constructor
*
* @param array $array
*/
public function __construct($array){
if(!is_array($array)){
throw new Exception('array2xml requires an array', 1);
unset($this);
}
if(!count($array)){
throw new Exception('array is empty', 2);
unset($this);
}
$this->data = new DOMDocument('1.0');
$this->dom_tree = $this->data->createElement('result');
$this->data->appendChild($this->dom_tree);
$this->recurse_node($array, $this->dom_tree);
}
/**
* recurse a nested array and return dom back
*
* @param array $data
* @param dom element $obj
*/
private function recurse_node($data, $obj){
$i = 0;
foreach($data as $key=>$value){
if(is_array($value)){
//recurse if neccisary
$sub_obj[$i] = $this->data->createElement($key);
$obj->appendChild($sub_obj[$i]);
$this->recurse_node($value, $sub_obj[$i]);
} elseif(is_object($value)) {
//no object support so just say what it is
$sub_obj[$i] = $this->data->createElement($key, 'Object: "'
. $key . '" type: "' . get_class($value) . '"');
$obj->appendChild($sub_obj[$i]);
} else {
//straight up data, no weirdness
$sub_obj[$i] = $this->data->createElement($key, $value);
$obj->appendChild($sub_obj[$i]);
}
$i++;
}
}
/**
* get the finished xml
*
* @return string
*/
public function saveXML(){
return $this->data->saveXML();
}
}
$test = array(
'cat'=>'animal',
'container'=> array(
'thing'=>'stuff',
'thing2'=>'stuff2',
'thing3'=>3,
'thing4'=>4,
'wtf'=> new stdClass(),
),
'foo'=>'bar',
);
var_dump($test);
try {
$o_test = new array2xml($test);
} catch (Exception $e) {
echo $e->getMessage();
}
echo $o_test->saveXML();
?>