Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active September 15, 2019 04:26
Show Gist options
  • Select an option

  • Save stemar/bed52c2555bb1f13838e0cbd03638b18 to your computer and use it in GitHub Desktop.

Select an option

Save stemar/bed52c2555bb1f13838e0cbd03638b18 to your computer and use it in GitHub Desktop.
Convert XML string to JSON string, formatted or not.
<?php
function xml_to_json($xml, $formatted=TRUE) {
$options = (bool)$formatted ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : 0;
return json_encode(simplexml_load_string($xml), $options);
}
<?php
$xml = '<Nodes><Node id="1">Content 1</Node><Node id="2">Content 2</Node></Nodes>';
echo xml_to_json($xml);
/*
{
"Node": [
"Content 1",
"Content 2"
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment