Skip to content

Instantly share code, notes, and snippets.

@barryvdh
Last active January 14, 2021 09:10
Show Gist options
  • Save barryvdh/1cc31ca91932f29ec510b3efddfa7309 to your computer and use it in GitHub Desktop.
Save barryvdh/1cc31ca91932f29ec510b3efddfa7309 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) {
if (is_array($childValue)) {
static::arrayToXml($childValue, $xml->addChild($key));
} else {
$xml->addChild($key, htmlspecialchars($childValue, ENT_XML1, 'UTF-8'));
}
}
} else {
$xml->$key = $value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment