Convert SimpleXML to JSON PHP
Solution 1
You can use json_encode. http://php.net/manual/en/function.json-encode.php
json_encode($array)
Solution 2
Here is why this is a very bad idea.
$xml = '<root><test><line code="line1">hello</line><line code="line2">world</line></test></root>';
$element = new \SimpleXMLElement($xml);
$json = json_encode($element);
If you look at the output of json_encode
, it will be as follows:
{"test":{"line":["hello","world"]}}
You just lost all of your attributes due to having repeated elements. There is no "simple" solution, you have to use a custom piece of code that will cycle through each element and format it properly. If you do try to access the element through $element
, you can still get the attributes because SimpleXML is not a regular PHP class.
I came up with a solution that will work for the example I gave, and for typical problems, although it does not handle namespaces.
calamansi_grenade
Updated on June 08, 2022Comments
-
calamansi_grenade almost 2 years
I am using Bigbluebutton's PHP API and I want to get all meeting sessions. In calling the method to display the meetings, I get this output:
Array ( [returncode] => SimpleXMLElement Object ( [0] => SUCCESS ) [messageKey] => SimpleXMLElement Object ( ) [message] => SimpleXMLElement Object ( ) [0] => Array ( [meetingId] => SimpleXMLElement Object ( [0] => as's meeting ) [meetingName] => SimpleXMLElement Object ( [0] => as's meeting ) [createTime] => SimpleXMLElement Object ( [0] => 1380878550574 ) [attendeePw] => SimpleXMLElement Object ( [0] => ap ) [moderatorPw] => SimpleXMLElement Object ( [0] => mp ) [hasBeenForciblyEnded] => SimpleXMLElement Object ( [0] => false ) [running] => SimpleXMLElement Object ( [0] => false ) ) [1] => Array ( [meetingId] => SimpleXMLElement Object ( [0] => XYZ's meeting ) [meetingName] => SimpleXMLElement Object ( [0] => XYZ's meeting ) [createTime] => SimpleXMLElement Object ( [0] => 1380879253000 ) [attendeePw] => SimpleXMLElement Object ( [0] => ap ) [moderatorPw] => SimpleXMLElement Object ( [0] => mp ) [hasBeenForciblyEnded] => SimpleXMLElement Object ( [0] => false ) [running] => SimpleXMLElement Object ( [0] => true ) ) )
How can I turn this simplexml top json?