Skip to content

Instantly share code, notes, and snippets.

@paulferrett
Created December 23, 2013 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paulferrett/8103667 to your computer and use it in GitHub Desktop.
Save paulferrett/8103667 to your computer and use it in GitHub Desktop.
Super simple class to encode an object into XML.
<?php
class XML {
/**
* Encode an object as XML string
*
* @param Object $obj
* @param string $root_node
* @return string $xml
*/
public function encodeObj($obj, $root_node = 'response') {
$xml = '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL;
$xml .= self::encode($obj, $root_node, $depth = 0);
return $xml;
}
/**
* Encode an object as XML string
*
* @param Object|array $data
* @param string $root_node
* @param int $depth Used for indentation
* @return string $xml
*/
private function encode($data, $node, $depth) {
$xml = str_repeat("\t", $depth);
$xml .= "<{$node}>" . PHP_EOL;
foreach($data as $key => $val) {
if(is_array($val) || is_object($val)) {
$xml .= self::encode($val, $key, ($depth + 1));
} else {
$xml .= str_repeat("\t", ($depth + 1));
$xml .= "<{$key}>" . htmlspecialchars($val) . "</{$key}>" . PHP_EOL;
}
}
$xml .= str_repeat("\t", $depth);
$xml .= "</{$node}>" . PHP_EOL;
return $xml;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment