How convert xml with namespaces to php array?

Member

by domenico , in category: PHP General , a year ago

How convert xml with namespaces to php array?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , a year ago

@domenico 

You can use the SimpleXMLElement class in PHP to convert an XML file with namespaces to a PHP array. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$xml = <<<XML
<root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2">
    <ns1:element1>Value 1</ns1:element1>
    <ns2:element2>Value 2</ns2:element2>
</root>
XML;

// Create SimpleXMLElement object
$simpleXml = new SimpleXMLElement($xml);

// Convert XML to PHP array
$json = json_encode($simpleXml);
$array = json_decode($json, true);

print_r($array);


This will output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Array
(
    [@attributes] => Array
        (
            [xmlns:ns1] => http://example.com/ns1
            [xmlns:ns2] => http://example.com/ns2
        )

    [ns1:element1] => Value 1
    [ns2:element2] => Value 2
)


Note that the namespace prefixes are included in the array keys. If you want to remove the prefixes, you can loop through the array and manually update the keys.

Related Threads:

How to convert xml into array of objects in php?
How to convert a php stdclass object to xml?
How to convert xml to json using php?
How to parse a xml string to array in php?
How to parse xml data to array using php?
How to parse xml data to array using php?