Created
March 11, 2019 16:11
-
-
Save wirwolf/377e645ea8ceb251ac502793f279a62e to your computer and use it in GitHub Desktop.
php xml to array
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 | |
function xmlToArray(string $xml) | |
{ | |
$doc = new DOMDocument(); | |
$doc->loadXML($xml); | |
$root = $doc->documentElement; | |
$output = domNodeToArray($root); | |
$output['@root'] = $root->tagName; | |
return $output; | |
} | |
function domNodeToArray($node) | |
{ | |
$output = []; | |
switch ($node->nodeType) { | |
case XML_CDATA_SECTION_NODE: | |
case XML_TEXT_NODE: | |
$output = trim($node->textContent); | |
break; | |
case XML_ELEMENT_NODE: | |
for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) { | |
$child = $node->childNodes->item($i); | |
$v = domNodeToArray($child); | |
if (isset($child->tagName)) { | |
$t = $child->tagName; | |
if (!isset($output[$t])) { | |
$output[$t] = []; | |
} | |
$output[$t][] = $v; | |
} elseif ($v || $v === '0') { | |
$output = (string)$v; | |
} | |
} | |
if ($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array | |
$output = ['@content' => $output]; //Change output into an array. | |
} | |
if (is_array($output)) { | |
if ($node->attributes->length) { | |
$a = []; | |
foreach ($node->attributes as $attrName => $attrNode) { | |
$a[$attrName] = (string)$attrNode->value; | |
} | |
$output['@attributes'] = $a; | |
} | |
foreach ($output as $t => $v) { | |
if (is_array($v) && count($v) === 1 && $t !== '@attributes') { | |
$output[$t] = $v[0]; | |
} | |
} | |
} | |
break; | |
} | |
return $output; | |
} | |
$xml_string = <<<XML | |
<?xml version='1.0' standalone='yes'?> | |
<movies> | |
<movie> | |
<rating type="thumbs">7</rating> | |
<rating type="stars">5</rating> | |
</movie> | |
</movies> | |
XML; | |
$t = xmlToArray($xml_string); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment