Skip to content

Instantly share code, notes, and snippets.

@softquantum
Forked from barryvdh/Xml.php
Created February 9, 2017 20:30
Show Gist options
  • Save softquantum/ba84a68c0c171c001da41aa6ee728b04 to your computer and use it in GitHub Desktop.
Save softquantum/ba84a68c0c171c001da41aa6ee728b04 to your computer and use it in GitHub Desktop.
XML Helper (from/to array)
<?php
use SimpleXMLElement;
class Xml {
/**
* @param array $data
* @param string $root
* @return SimpleXMLElement
*/
public static function fromArray(array $data, $root = 'xml') : SimpleXMLElement
{
$xmlData = sprintf('<?xml version="1.0" encoding="UTF-8"?><%s/>', $root);
$xml = new SimpleXMLElement($xmlData);
static::arrayToXml($data, $xml);
return $xml;
}
/**
* @param string $xmlString
* @return array
*/
public static function toArray($xmlString) : array
{
$xml = simplexml_load_string($xmlString, null, LIBXML_NOCDATA);
return json_decode(json_encode($xml), true);
}
public static function prettyPrint($xml) : string
{
if ($xml instanceof SimpleXMLElement) {
$xml = $xml->asXML();
}
$domxml = new \DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml);
return $domxml->saveXML();
}
/**
* @param array $data
* @param SimpleXMLElement $xml
*/
private static function arrayToXml(array $data, SimpleXMLElement $xml)
{
foreach($data as $key => $value) {
if(is_array($value)) {
if (!is_numeric(key($value))) {
$value = [$value];
}
// For numeric items, add each as the same key
foreach ($value as $childValue) {
static::arrayToXml($childValue, $xml->addChild($key));
}
} else {
$xml->addChild($key, $value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment