Created
October 26, 2023 05:32
-
-
Save amrography/6047cbc558a49325c7b7915051f4aec2 to your computer and use it in GitHub Desktop.
array_to_xml.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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