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:

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:

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.