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,
- Attributes stored as key value pairs under [‘tag_name’][‘@attributes’]
- CDATA nodes are stored under [‘tag_name’][‘@cdata’]
- 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.
$xml_data= "<?xml version="1.0" encoding="UTF-8"?>
<body>Don't forget me this weekend!</body> </note>"
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..
$array = XML2Array::createArray($xml);