Created
February 15, 2016 04:02
-
-
Save tomzx/21917d17cbaec50bf793 to your computer and use it in GitHub Desktop.
PHP xml2js (attributes to $, nodeValue to _)
This file contains hidden or 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 xml2js($xmlnode) | |
{ | |
$root = func_num_args() <= 1; | |
$jsnode = []; | |
if ($root) { | |
$nodename = $xmlnode->getName(); | |
$jsnode[$nodename] = xml2js($xmlnode, true); | |
return json_encode($jsnode, JSON_PRETTY_PRINT); | |
} | |
if (count($xmlnode->attributes()) > 0) { | |
$jsnode["$"] = []; | |
foreach ($xmlnode->attributes() as $key => $value) { | |
$jsnode["$"][$key] = (string)$value; | |
} | |
} | |
$textcontent = trim((string)$xmlnode); | |
if ($textcontent) { | |
$jsnode["_"] = $textcontent; | |
return $jsnode; | |
} | |
foreach ($xmlnode->children() as $childxmlnode) { | |
$childname = $childxmlnode->getName(); | |
$jsnode[$childname][] = xml2js($childxmlnode, true); | |
} | |
return $jsnode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment