Skip to content

Instantly share code, notes, and snippets.

@felipevolpatto
Last active December 28, 2015 19:29
Show Gist options
  • Save felipevolpatto/7550485 to your computer and use it in GitHub Desktop.
Save felipevolpatto/7550485 to your computer and use it in GitHub Desktop.
Array to XML helper.
<?php
class ArrayHelper {
const PARENT_NODE = "<return></return>";
private function __construct() { }
public static function arrayToXml($array, &$xml) {
foreach($array as $key => $value) {
if(is_array($value)) {
if (is_numeric($key)) {
$subnode = $xml;
} else {
$key = strtolower($key);
$subnode = $xml->addChild("$key");
}
self::arrayToXml($value, $subnode);
}
else {
if ($value != "")
$value = html_entity_decode($value);
$key = is_numeric($key) ? "item" : strtolower($key);
self::safeAddChild($xml, "$key", "$value");
}
}
}
public static function &safeAddChild(&$sxml, $name, $value) {
$safeValue = preg_replace('/&(?!\w+;)/', '&amp;', $value);
return $sxml->addChild($name, $safeValue);
}
public static function xmlJoin($root, $append) {
if ($append) {
if (strlen(trim((string) $append)) == 0) {
$xml = $root->addChild($append->getName());
foreach($append->children() as $child) {
xml_join($xml, $child);
}
} else {
$xml = $root->addChild($append->getName(), (string) $append);
}
foreach($append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
public static function executeArrayToXml(array $object, $typePlural = 'orders') {
$array = self::addParentTo($typePlural, ($object);
$xml = new \SimpleXMLElement("<?xml version=\"1.0\"?>" . self::PARENT_NODE);
self::arrayToXml($array, $xml);
return $xml->asXML();
}
public static function addParentTo($parent, $array) {
return array($parent => $array);
}
public static function in_arrayInsensitive($needle, $haystack) {
return in_array($needle, array_map('strtoupper', $haystack));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment