views:

5639

answers:

8

What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.

+1  A: 

Use a dom function to do it: http://www.php.net/manual/en/function.dom-import-simplexml.php

Import the SimpleXML object and then save. The above link contains an example. :)

In a nutshell:

<?php
$array = array('hello' => 'world', 'good' => 'morning');

$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><foo />");
foreach ($array as $k=>$v) {
  $xml->addChild($k, $v);
}
?>
Till
Why were I downvoted?
Till
I don't think this answers the question, I'm pretty sure he wants to do something like convert array("foo" => "bar") into "<xml><foo>bar</foo></xml>" (not exactly, but you get the idea)
davr
You can populate a simplexml object?
Till
But he didn't ask how to convert simplexml objects into xml, he wanted plain XML objects. Unless I misunderstood, I didn't see an easy way to turn an arbitrary PHP data structure (objects, arrays, strings etc) into a simplexml object (and thus into an XML string)
davr
Extended my answer.
Till
still doesn't answer it. you're giving an array, not an object. and even if you used `get_object_vars` first it wouldn't work recursively.
philfreo
A: 

Well, while a little dirty, you could always run a loop on the object's properties...

foreach($obj as $key => $val){
  $_xml .= "<".$key.">".$val."</".$key">\n";
}

Using fopen/fwrite/fclose you could generate an XML doc with the $_xml variable as content. It's ugly, but it would work.

Steve Paulo
Got a slight syntax error. No concatenation after the second $key.
Brandon Hansen
works, but if you need to handle objects more than 1 level deep try http://stackoverflow.com/questions/137021/php-object-as-xml-document/2194774#2194774
philfreo
+8  A: 

take a look at PEAR's XML_Serializer package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.

Should do the trick

arin sarkissian
+1 XML_Serializer is pretty cool.
Max
+2  A: 

I didn't do any XML <=> PHP-Objects conversion but if you just want a way to serialize your php obejcts then it is very simple, you can use php built-in json_encode() and json_decode() these functions take care of everything and your php objects are serialized as JSON.

These functions are available as of PHP 5.2.0 and above, if you use an older version then use PECL json:1.2.0-1.2.1

http://www.php.net/json_encode

Ahmad
+1  A: 

use WDDX: http://uk.php.net/manual/en/wddx.examples.php

(if this extension is installed)

it's dedicated to that:

http://www.openwddx.org/

A: 

not quite an answer to the original question, but the way i solved my problem with this was by declaring my object as:

$root = '<?xml version="1.0" encoding="UTF-8"?><Activities/>';
$object = new simpleXMLElement($root); 

as opposed to:

$object = new stdClass;

before i started adding any values!

significance
A: 

I'd agree with using PEAR's XML_Serializer, but if you want something simple that supports objects/arrays that have properties nested, you can use this.

class XMLSerializer {

    // functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/

    public static function generateValidXmlFromObj(stdClass $obj, $node_block='nodes', $node_name='node') {
        $arr = get_object_vars($obj);
        return self::generateValidXmlFromArray($arr, $node_block, $node_name);
    }

    public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {
        $xml = '<?xml version="1.0" encoding="UTF-8" ?>';

        $xml .= '<' . $node_block . '>';
        $xml .= self::generateXmlFromArray($array, $node_name);
        $xml .= '</' . $node_block . '>';

        return $xml;
    }

    private static function generateXmlFromArray($array, $node_name) {
        $xml = '';

        if (is_array($array) || is_object($array)) {
            foreach ($array as $key=>$value) {
                if (is_numeric($key)) {
                    $key = $node_name;
                }

                $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
            }
        } else {
            $xml = htmlspecialchars($array, ENT_QUOTES);
        }

        return $xml;
    }

}
philfreo
A: 

There is Another answer that talks about usage of WDDX. Bit its Voted Down too !! Is there any known problem with WDDX ?? I couldn't understand the reason behind voting down.