Advertisement
Guest User

James Hartig

a guest
Dec 2nd, 2010
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.70 KB | None | 0 0
  1. function toXML($object, $rootName="", $indexName="") {
  2.     $xmlDoc = new DOMDocument();
  3.    
  4.     if (!is_string($object)) { //we gotta hope its an array
  5.         if ($rootName) {
  6.             $root = $xmlDoc->appendChild(
  7.                     $xmlDoc->createElement($rootName));
  8.         }
  9.         $arrayParse = function($array, $root) use (&$arrayParse, &$xmlDoc, $indexName) {
  10.             foreach ($array as $key => $val) {
  11.                 if (is_array($val)) {
  12.                     if (is_numeric($key) && $indexName) {
  13.                         $newRoot = $root->appendChild(
  14.                                    $xmlDoc->createElement($indexName));
  15.                     } else if (is_numeric($key)) {
  16.                         $newRoot = $root->appendChild(
  17.                                    $xmlDoc->createElement("Object"));
  18.                     } else {
  19.                         $newRoot = $root->appendChild(
  20.                                    $xmlDoc->createElement($key));
  21.                     }                    
  22.                     $arrayParse($val, $newRoot);
  23.                 } else {
  24.                     $root->appendChild(
  25.                     $xmlDoc->createElement($key, $val));
  26.                 }                
  27.             }
  28.         };
  29.         if (isset($root)) {
  30.             $arrayParse($object, $root);
  31.         } else {
  32.             $arrayParse($object, $xmlDoc);
  33.         }
  34.     } else {
  35.         if ($rootName) {
  36.             $root = $xmlDoc->appendChild(
  37.                     $xmlDoc->createElement($rootName, $object));
  38.         } else {
  39.             $root = $xmlDoc->appendChild(
  40.                     $xmlDoc->createElement("Object", $object));
  41.         }
  42.     }
  43.     $xmlDoc->formatOutput = true;
  44.     return $xmlDoc->saveXML();        
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement