Skip to content

Instantly share code, notes, and snippets.

@mtdowling
Created October 12, 2012 06:54
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 mtdowling/3877687 to your computer and use it in GitHub Desktop.
Save mtdowling/3877687 to your computer and use it in GitHub Desktop.
XML to array using json_encode
<?php
// Note that this will not maintain XML attributes
function jsonXml2Array(SimpleXMLElement $xml)
{
return json_decode(json_encode($xml), true);
}
function jsonXml2ArrayWithNamespacedAttributes($xml)
{
// Gets rid of all namespace definitions and namespace references
return json_decode(json_encode(new \SimpleXMLElement(
preg_replace(array('/\sxmlns[^"]+"[^"]+"/', '/[a-zA-Z]+:([a-zA-Z]+[=>])/'), array('', '$1'), $xml)
)), true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment