Convert XML to Array in PHP Using XML2Array

Convert XML to array is very common functionality in PHP while working with web services.We are normally using XML type data for request and response between server and client communication.I am sharing this tutorial to convert xml to array in php using XML2Array lib class.

I have already shared a post How To Convert XML To Associative Array in PHP, In that post i am using simplexml_load_string() php function.

But, I am using XML2Array class for convert xml data into php array. XML2Array is a class which is use to convert XML to an array in PHP. It returns an php array which can be converted back to XML using the Array2XML class.This class use string XML as input or an object of type DOMDocument.

As per docs, There are following Conventions,

  1. Attributes stored as key value pairs under [‘tag_name’][‘@attributes’]
  2. CDATA nodes are stored under [‘tag_name’][‘@cdata’]
  3. In case a node has attributes, the value will be stored in [‘tag_name’][‘@value’]

Also checkout other related tutorials,

Simple Usage of XML2Array Class to Convert XML into Array

Step 1: Download XML2Array class from Here.

Step 2: We are using XML2Array libs to convert xml file data into the php array, Let’s download XML2Array library.

Step 3: Now we will create a php variable that will hold xml file content.The following code is defined a xml_data name variable and assigned xml file content.

Step 4: Create php array data from xml file using inbuilt createArray() method, This method takes a variable that hold xml file content, we ll pass xml file as a variable on it..

Demo & Download Source Code Of Convert XMl to Array in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.