note 79125 added to ref.dom

From: Date: Mon, 12 Nov 2007 23:12:26 +0000
Subject: note 79125 added to ref.dom
Groups: php.notes 
Request: Send a blank email to php-notes+get-132210@lists.php.net to get a copy of this message
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(); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 208.67.191.194 ---- Manual Page -- http://www.php.net/manual/en/ref.dom.php Edit -- https://master.php.net/note/edit/79125 Del: integrated -- https://master.php.net/note/delete/79125/integrated Del: useless -- https://master.php.net/note/delete/79125/useless Del: bad code -- https://master.php.net/note/delete/79125/bad+code Del: spam -- https://master.php.net/note/delete/79125/spam Del: non-english -- https://master.php.net/note/delete/79125/non-english Del: in docs -- https://master.php.net/note/delete/79125/in+docs Del: other reasons-- https://master.php.net/note/delete/79125 Reject -- https://master.php.net/note/reject/79125 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132210) next »