I need to convert an XML document into JSON, in order to easily access the data in JavaScript. I am currently using this method to convert the XML into JSON:
json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));
However, I ran into a problem when an element only contains 1 child element. When it is parsed with SimpleXML, it is treated as an object instead of an array. I want them to always be treated as arrays, unless the element only contains text.
Example:
$xml = <<<END
<xml>
<TESTS>
<TEST>TEXT HERE</TEST>
</TESTS>
</xml>
END;
echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));
This outputs:
{"TESTS":{"TEST":"TEXT HERE"}}
If I add another element under , then the output is how I want it:
$xml = <<<END
<xml>
<TESTS>
<TEST>TEXT HERE</TEST>
<TEST>MORE TEXT HERE</TEST>
</TESTS>
</xml>
END;
echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));
Output:
{"TESTS":{"TEST":["TEXT HERE","TEXT HERE"]}}
Note how the elements are contained inside a JSON array instead of a JSON object. Is there a way to force elements to be parsed as arrays?