Does anybody know a quick way to convert a SimpleXMLElement to a normal STDClass object, without iterating through each branch manually? I would feel better working with a normal object after fetching the data.
            Asked
            
        
        
            Active
            
        
            Viewed 1.7k times
        
    23
            
            
        - 
                    You mean importing all the public properties of that SimpleXMLElement? Quick is relative :) – Flavius Oct 18 '09 at 12:15
 - 
                    You would "feel better" isn't a valid reason imo :) What's the real reason for you to want a stdClass to work with? – chelmertz Oct 18 '09 at 12:23
 - 
                    6Well, I am fetching data from an XML file and processing it afterwards in quite a complex system. From that point I do not need any XML/SimpleXML specific behaviour, but just the raw data. PHP's XML functions tend not to be as well documented as the other parts of the language, and I fear unexpected behaviour when manipulating the data along the way with it still being a simpleXML element. With a STDClass, I know what to expect, how to manipulate it, validate the data and so on. That is the long version of "feel better". Feel better? :) – Pekka Oct 18 '09 at 13:14
 
4 Answers
75
            
            
        $my_std_class = json_decode(json_encode($my_simplexmlelement));
$my_assoc_array = json_decode(json_encode($my_simplexmlelement), true);
        Skyler Johnson
        
- 3,833
 - 1
 - 20
 - 6
 
- 
                    2+1, This should definitely be the chosen answer. The reason I needed to convert it to stdClass was because Drupal has issues with the SimpleXmlElement object. – Jason Fuller Mar 21 '13 at 20:54
 - 
                    
 - 
                    this results in converting SimpleXMLElement class member variables such as "MemberTypeArray" to "membertypearray" (lowercase) how do i avoid this ? and use this function to covert it to a std class ? – mahen3d Oct 26 '15 at 05:53
 
6
            I suggest looking into using XMLReader, which lends itself well to extracting data and storing it as whatever data type one wishes, instead of SimpleXML. It's especially good for regularly-used documents (I use it, extended as RSSReader, for RSS), is much faster than might be expected, and as a bonus uses less memory than SimpleXML.
        GZipp
        
- 5,386
 - 1
 - 22
 - 18
 
2
            
            
        Another way is:
(object)(array)$my_simplexmlelement
Unfortunately if you have children they remain as SimpleXMLElement
        Capy
        
- 5,167
 - 2
 - 20
 - 21
 
1
            
            
        I don't know if there's a way to convert the object without iterating through it. My guess is that you can't.
You can check this thread out, it shows you how to convert a SimpleXML to an array, you can adapt that.
        Community
        
- 1
 - 1
 
        Alex Ciminian
        
- 11,398
 - 15
 - 60
 - 94