Converting an XML Object to Associative Array in PHP

Let’s say you have an XML file (like the one that follows) that you want to turn into an associative array in PHP. Doing this takes a few steps but it’s actually quite simple. I’m using a quiz questions XML file as an example throughout this article, I think the real world aspect of it makes it a little more understandable.

First let’s take a look at the XML file:

Invalid GitHub Gist source. Please check your source.

Basically our plan is to turn this XML file into an object, then json_encode() that object and then json_decode() that object right after to just turn it into an array. Finally, since the example above would be an array like follows:

array(1) { [“quizQuestion”]=> array(3) { … all our actual questions are in here… } }

We need to make our array equal to the $xml_array[“quizQuestion”] element, that way our array will be:

array(3) { [0]=> array(4) { [“question”]=> string(118) “Tyler Durden is a ficitional character appearing as the central protagonist and antagonist in what 1999 American film?” [“answer”]=> string(10) “Fight Club” [“categories”]=> string(19) “Pop Culture, Movies” [“difficulty”]=> string(1) “2” } …more questions here… }

The final code to achieve this is as follows:

Invalid GitHub Gist source. Please check your source.

As always thank you for reading and please share this article around around as much as you can! Please feel free to put any suggestions or ideas for future articles in the comments section below, and please let me know if I’ve made any mistakes in the code. I have a working version of a quiz game online but I copy pasted some of this so who knows if it’s still all there that needs to be there.

Posted in PHP