note 105997 deleted from book.simplexml by danbrown
| From: | danbrown@php.net | Date: | Fri, 30 Sep 2011 21:23:47 +0000 |
| Subject: | note 105997 deleted from book.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183550@lists.php.net to get a copy of this message | ||
Note Submitter: salvocucinella at gmail dot com
----
Here is a snippet to convert a simple object to XML.
A class that does the job and an example how to use it
<?php
class Obj2xml {
var $xmlResult;
function __construct($rootNode){
$this->xmlResult = new SimpleXMLElement("<$rootNode></$rootNode>");
}
private function iteratechildren($object,$xml){
foreach ($object as $name=>$value) {
if (is_string($value) || is_numeric($value)) {
$xml->$name=$value;
} else {
$xml->$name=null;
$this->iteratechildren($value,$xml->$name);
}
}
}
function toXml($object) {
$this->iteratechildren($object,$this->xmlResult);
return $this->xmlResult->asXML();
}
}
//----test object----
$ob->campo1=10;
$ob->campo2->campo21="campo21";
$ob->campo2->campo22="campo22";
//----test object----
$converter=new Obj2xml("root");
header("Content-Type:text/xml");
echo $converter->toXml($ob);
?>