Skip to content

Instantly share code, notes, and snippets.

@amrography
Created October 26, 2023 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amrography/6047cbc558a49325c7b7915051f4aec2 to your computer and use it in GitHub Desktop.
Save amrography/6047cbc558a49325c7b7915051f4aec2 to your computer and use it in GitHub Desktop.
array_to_xml.php
<?php
use App\Services\AvroService;
require 'vendor/autoload.php';
$wrapper = <<<XML
<root />
XML;
$xml = new SimpleXMLElement($wrapper);
arrayToXml([], true), $xml);
echo $xml->asXML();
function arrayToXml($array, &$xml){
foreach ($array as $key => $value) {
if(is_int($key)){
$key = $xml->getName();
}
if (strpos($key, '@') === 0) {
$xml->addAttribute(substr($key, 1), $value);
} elseif ($key == '$') {
// skip
} elseif(is_array($value)){
if (isset($value['$'])) {
$label = $xml->addChild($key, $value['$']);
} else {
// if keys are numeric then don't create node
// dump(array_keys($value));
$label = $xml->addChild($key);
}
arrayToXml($value, $label);
} else {
$xml->addChild($key, $value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment