I'm trying to convert some XML to JSON, which is easy enough with PHP
$file = file_get_contents('data.xml' );
$a = json_decode(json_encode((array) simplexml_load_string($file)),1);
print_r($a);
Taking the following XML
<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar>
<one lang="fr" type="bar">Test</one>
<one lang="fr" type="foo">Test</one>
<one lang="fr" type="baz">Test</one>
</bar>
<thunk>
<thud>
<bar lang="fr" name="bob">test</bar>
<bar lang="bz" name="frank">test</bar>
<bar lang="ar" name="alive">test</bar>
<bar lang="fr" name="bob">test</bar>
</thud>
</thunk>
</foo>
And paring it through simplexml produces
Array
(
[bar] => Array
(
[one] => Array
(
[0] => Test
[1] => Test
[2] => Test
)
)
[thunk] => Array
(
[thud] => Array
(
[bar] => Array
(
[0] => test
[1] => test
[2] => test
[3] => test
)
)
)
)
Where ideally the output would look like this
{
"foo": {
"bar": {
"one": [
{
"_lang": "fr",
"_type": "bar",
"__text": "Test"
},
{
"_lang": "fr",
"_type": "foo",
"__text": "Test"
},
{
"_lang": "fr",
"_type": "baz",
"__text": "Test"
}
]
},
"thunk": {
"thud": {
"bar": [
{
"_lang": "fr",
"_name": "bob",
"__text": "test"
},
{
"_lang": "bz",
"_name": "frank",
"__text": "test"
},
{
"_lang": "ar",
"_name": "alive",
"__text": "test"
},
{
"_lang": "fr",
"_name": "bob",
"__text": "test"
}
]
}
}
}
}
Trouble is that the output doesn't contain all the attributes for the child elements, some of these elements contain two or more attributes, is there a way to transform the xml with PHP or Python and include all the attributes found in all the children?
Thanks