Skip to content

Instantly share code, notes, and snippets.

@tomzx
Created February 15, 2016 04:02
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 tomzx/21917d17cbaec50bf793 to your computer and use it in GitHub Desktop.
Save tomzx/21917d17cbaec50bf793 to your computer and use it in GitHub Desktop.
PHP xml2js (attributes to $, nodeValue to _)
<?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