Skip to content

Instantly share code, notes, and snippets.

@duncte123
Forked from paulferrett/simple_xml_encode.php
Last active December 9, 2017 17:38
Show Gist options
  • Save duncte123/b06292c8fba8fa5ebd0b005718e6a16f to your computer and use it in GitHub Desktop.
Save duncte123/b06292c8fba8fa5ebd0b005718e6a16f 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 static 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 $node
* @param int $depth Used for indentation
* @return string $xml
*/
private static 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