How to Parses XML data into an array in PHP ?


There are several ways to parse XML data into an array in PHP. Here are three methods:

Method 1: Using SimpleXML

SimpleXML is a built-in PHP extension that provides an easy way to get an XML element as an object. You can then convert this object to an array using the json_decode() function.

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json, true);

In this example, $xml_string is the XML data that you want to parse. The simplexml_load_string() function converts the XML string into a SimpleXML object. The json_encode() function then converts this object into a JSON string, which can be decoded into an array using the json_decode() function.

Method 2: Using DOMDocument

The DOMDocument class is another built-in PHP class that can be used to parse XML data. You can use the getElementsByTagName() method to get all the elements of a particular tag name and then loop through them to create an array.

$xml = new DOMDocument();
$xml->loadXML($xml_string);
$elements = $xml->getElementsByTagName('element_name');
$array = array();
foreach ($elements as $element) {
    $array[] = array(
        'attribute_name' => $element->getAttribute('attribute_name'),
        'value' => $element->nodeValue
    );
}

In this example, $xml_string is the XML data that you want to parse. The loadXML() method of the DOMDocument class loads the XML data into the object. The getElementsByTagName() method gets all the elements with the specified tag name. The getAttribute() method gets the value of an attribute of an element, and the nodeValue property gets the text content of an element.

Method 3: Using XMLReader

The XMLReader class is a low-level PHP class that provides a fast and efficient way to parse large XML files. You can use the read() method to read the next node in the XML file and the getAttribute() method to get the value of an attribute.

$xml = new XMLReader();
$xml->open($xml_file);
$array = array();
while ($xml->read()) {
    if ($xml->nodeType == XMLReader::ELEMENT && $xml->name == 'element_name') {
        $element = array(
            'attribute_name' => $xml->getAttribute('attribute_name'),
            'value' => $xml->readString()
        );
        $array[] = $element;
    }
}

In this example, $xml_file is the path to the XML file that you want to parse. The open() method of the XMLReader class opens the file. The read() method reads the next node in the file. The nodeType property gets the type of the current node, and the name property gets the name of the current node. The getAttribute() method gets the value of an attribute of an element, and the readString() method gets the text content of an element.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.