Lautr

Convert Object of class stdClass to XML Object

October 13, 2010 09:29 I had to do that recently and since i didn't found anything PHP native to do it i had to code it myself, just 2 SMall Functions to Convert an stdClass Object in to an XML (Writer) Object, or an XML String at the End. /** * Adds Nodes to an Existing XML Writer Object * * @param XMLWriter $xml * @param string $nodeName * @param string | array | stdObject $nodeValue */ function _addNodeToXML(&$xml,$nodeName,$nodeValue){ if(is_array($nodeValue)){ $xml->startElement($nodeName); foreach($nodeValue as $nodeValueKey => $nodeValueValue){ _addNodeToXML($xml, $nodeValueKey, $nodeValueValue); } $xml->endElement(); }elseif(is_a($nodeValue,"stdClass")){ $xml->startElement("item"); foreach($nodeValue as $nodeValueKey => $nodeValueValue){ _addNodeToXML($xml, $nodeValueKey, $nodeValueValue); } $xml->endElement(); }else{ $xml->writeElement($nodeName,$nodeValue); } } /** * Converts an Object of stdClass to an XML (XMLWriter) “Object” * * @param stdClass|array $stdClass * @return s */ function _stdClassToXML($stdClass){ $xml = new XMLWriter(); $xml->openMemory(); _addNodeToXML($xml,"root",$stdClass); return $xml->outputMemory(); }
HannesMarch 13, 2012 17:17 Hey JOhn, it should work with nested stdclass objects, take a look & try: http://pastebin.com/GYvx63AW
JOhnMarch 13, 2012 14:47 Hi Hannes

Thank you for your code however I am having some trouble with it. I just don't know objects well enough. Could you please help me implement if I sent you some code. I would be very grateful.

I want to turn the wsdl response on this page "http://jmdd.co.uk/zz_fundlolly/reports/aw_affiliate_client.php" into xml that I can parse using simpleXML.

Thanks
John