Skip to content

Instantly share code, notes, and snippets.

@Ellrion
Created March 13, 2018 09:25
Show Gist options
  • Save Ellrion/dcfbb560a175c845749f43087aa03be2 to your computer and use it in GitHub Desktop.
Save Ellrion/dcfbb560a175c845749f43087aa03be2 to your computer and use it in GitHub Desktop.
array to xml string and xml string to array helpers
<?php
if (!function_exists('array2xml')) {
/**
* Конвертирует массив в xml
*
* @param $array
* @param null|string|SimpleXMLElement $root
* @param string $version
* @param string $encoding
*
* @return SimpleXMLElement
*/
function array2xml($array, $root = null, $version = '1.0', $encoding = 'UTF-8')
{
if (!($root instanceof \SimpleXMLElement)) {
$rootName = is_string($root) ? $root : 'root';
$root = new \SimpleXMLElement('<?xml version="' . $version . '" encoding="' . $encoding . '" ?><' . $rootName . '></' . $rootName . '>');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
$sub_node = $root->addChild(is_numeric($key) ? 'item' . $key : (string) $key);
array2xml($value, $sub_node);
} else {
$root->addChild((string) $key, htmlspecialchars((string) $value));
}
}
return $root->asXML();
}
}
if (!function_exists('xml2array')) {
/**
* Конвертирует xml в массив
*
* @param string|SimpleXMLElement $xml
* @param bool $simplifyFlag
* @param array $array
*
* @return array
*/
function xml2array($xml, $simplifyFlag = true, $array = [])
{
if (!($xml instanceof \SimpleXMLElement)) {
$xml = new \SimpleXMLElement((string) $xml);
}
foreach ($xml->attributes() as $attr => $val) {
$array['@attributes'][$attr] = (string) $val;
}
$has_child = false;
foreach ($xml as $index => $node) {
$has_child = true;
$array[$index][] = xml2array($node, $simplifyFlag);
}
if (!$has_child) {
$array['@value'] = (string) $xml;
}
foreach ($array as $key => $val) {
if (is_array($val) && count($val) === 1 && array_key_exists(0, $val)) {
if ($simplifyFlag && isset($val[0]['@value'])) {
$array[$key] = $val[0]['@value'];
} else {
$array[$key] = $val[0];
}
}
}
return $array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment