easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode(array = json_decode($json,TRUE);
Answer from user1398287 on Stack Overflow
๐ŸŒ
GitHub
github.com โ€บ spatie โ€บ array-to-xml
GitHub - spatie/array-to-xml: A simple class to convert an array to xml ยท GitHub
By default all spaces in the key names of your array will be converted to underscores. If you want to opt out of this behaviour you can set the third argument to false.
Starred by 1.2K users
Forked by 214 users
Languages ย  PHP
๐ŸŒ
Packagist
packagist.org โ€บ packages โ€บ mtownsend โ€บ xml-to-array
mtownsend/xml-to-array - Packagist.org
$xml = <<<XML <?xml version="1.0"?> <request> <carrier>fedex</carrier> <id>123</id> <tracking_number>9205590164917312751089</tracking_number> </request> XML; $array = xml_to_array($xml); // $array is: [ 'carrier' => 'fedex', 'id' => '123', 'tracking_number' => '9205590164917312751089' ];
๐ŸŒ
GitHub
github.com โ€บ vyuldashev โ€บ xml-to-array
GitHub - vyuldashev/xml-to-array: A simple class to convert an xml to array
use Vyuldashev\XmlToArray\XmlToArray; $xml = '<items> <good_guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </good_guy> <bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </bad_guy> </items>'; $result = XmlToArray::convert($xml); After running this piece of code $result will contain: array:1 [ "items" => array:2 [ "good_guy" => array:2 [ "name" => "Luke Skywalker" "weapon" => "Lightsaber" ] "bad_guy" => array:2 [ "name" => "Sauron" "weapon" => "Evil Eye" ] ] ]
Starred by 36 users
Forked by 15 users
Languages ย  PHP 100.0% | PHP 100.0%
๐ŸŒ
Laravel News
laravel-news.com โ€บ home โ€บ laravel packages โ€บ simple xml converter package for php
Simple XML Converter Package for PHP - Laravel News
September 9, 2025 - The XML Converter Package for PHP by Novak Uroลกeviฤ‡ provides a simple helper to convert XML data into JSON and PHP arrays.
๐ŸŒ
ItSolutionstuff
itsolutionstuff.com โ€บ post โ€บ how-to-read-xml-file-in-laravelexample.html
How to Read XML File in Laravel? - ItSolutionstuff.com
April 16, 2024 - You can easily read xml file in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version. In this example, i will give you very simple example of convert xml to php array in laravel.
Find elsewhere
๐ŸŒ
Packagist
packagist.org โ€บ packages โ€บ vyuldashev โ€บ xml-to-array
vyuldashev/xml-to-array - Packagist.org
December 24, 2025 - use Vyuldashev\XmlToArray\XmlToArray; $xml = '<items> <good_guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </good_guy> <bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </bad_guy> </items>'; $result = XmlToArray::convert($xml); After running this piece of code $result will contain: array:1 [ "items" => array:2 [ "good_guy" => array:2 [ "name" => "Luke Skywalker" "weapon" => "Lightsaber" ] "bad_guy" => array:2 [ "name" => "Sauron" "weapon" => "Evil Eye" ] ] ]
๐ŸŒ
Laravel.io
laravel.io โ€บ forum โ€บ 11-03-2015-xml-to-jsonarray-for-storage
XML to JSON/Array for Storage | Laravel.io
Sign in to participate in this thread! ... The Laravel portal for problem solving, knowledge sharing and community building.
Top answer
1 of 2
27

Welcome to the world of xml! The way you are doing it is the best way that I am currently aware of. A basic example of xml to json is the way you are doing it:

$xml = simplexml_load_string($xml_string);

$json = json_encode($xml);

$array = json_decode($json,TRUE);

I do see that you are type-hinting array before your simplexml_load_string call. Is there a reason for that?

Also when you state that you are not sure how to run the comparison, what exactly do you mean by that? Is your xml static, meaning never changing, or does it change in size and/or scope?

2 of 2
1

I created a package that works very well with Laravel to help you convert XML into an array.

https://github.com/mtownsend5512/xml-to-array

Install it, and you can make use of the global helper function for Laravel xml_to_array.

Because your XML is malformed, I tried my best to fix it so I could provide an example:

    $xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<community ID="1234" POSTDATE="20180329"
    xmlns="" COMPANY="SAMPLE CO">
    <data1>
        <datatype ID="0001">
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
        </datatype>
        <datatype ID="0002">
            <utpricing LT="2" STARTDATE="20160102" ENDDATE="20170102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
            <utpricing LT="1" STARTDATE="20150102" ENDDATE="20160102" BASEAMOUNT="99" CONCESSION="0.00" EFFAMOUNT="99" CONTYPE="SAMPLE" CONVALUE="0.00"/>
        </datatype>
    </data1>
    <data2>
        <data2 ID="141" NAME="IAM | 1 | 1.00" SQFTMIN="111" SQFTMAX="222"/>
        <data2 ID="142" NAME="ASA | 1 | 1.00" SQFTMIN="111" SQFTMAX="222"/>
        <data2 ID="143" NAME="MPL | 1 | 1.00" SQFTMIN="111" SQFTMAX="222"/>
        <data2 ID="144" NAME="EBI | 1 | 1.00" SQFTMIN="111" SQFTMAX="222"/>
        <data2 ID="145" NAME="TOF | 2 | 2.00" SQFTMIN="111" SQFTMAX="222"/>
    </data2>
    <samples>
        <sample ID="001" AVAILDATE="20152901" STATUS="Unavailable" data1TYPE="001" UNITCAT="1X1" SOMEVALUE="50.00" data2ID="141">
            <item1 ID="59" item2="50.00" DESCRIPTION="Sample Description"/>
            <offeredterm LT="2" BASEAMOUNT="1120.00" TOTALCONCESSION="0.00" EFFECTIVESAMPLE="1120.00" CONTYPE="T" CONVALUE="0.00"/>
        </sample>
        <sample ID="002" AVAILDATE="20152901" STATUS="Unavailable" data1TYPE="001" UNITCAT="1X1" SOMEVALUE="50.00" data2ID="141">
            <item1 ID="59" item2="50.00" DESCRIPTION="Sample Description"/>
            <offeredterm LT="2" BASEAMOUNT="1120.00" TOTALCONCESSION="0.00" EFFECTIVESAMPLE="1120.00" CONTYPE="T" CONVALUE="0.00"/>
        </sample>
    </samples>
</community>
XML;

dd(xml_to_array($xml));

Now your XML will be a valid array which can be manipulated. Because of your extensive use of attributes you will have a lot of data clean up to do. I recommend wrapping it in a Laravel Collection by doing collect($xml), then checking Laravel's Collection documentation to figure out the best way to transform the data in the way you want it.

๐ŸŒ
GitHub
github.com โ€บ PHPJunior โ€บ laravel-xml
GitHub - PHPJunior/laravel-xml: This package is a simple XML to Array converter for Laravel.
use Illuminate\Support\Arr; $data ... is a <strong>bio03</strong>', 'bio04' => 'This is a <strong>bio04</strong>', ]; $xml = Arr::toXml($data); <root> <name>John Doe</name> ... </root> // change root tag $xml = Arr::toXml($data, ...
Author ย  PHPJunior
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.xml-parse-into-struct.php
PHP: xml_parse_into_struct - Manual
This function parses an XML string into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array.
๐ŸŒ
Codementor
codementor.io โ€บ community โ€บ convert multidimensional array to xml file in php
Convert multidimensional array to XML file in PHP | Codementor
July 12, 2019 - Instead of the database you can store the data in the XML file and retrieve data from XML file without connecting to the database. Website sitemap are also generate in XML format. In this tutorial, we will show you how to convert PHP multidimensional or associative array to the XML file, and the example code shows how to parse the XML file and convert XML data to array in PHP.
๐ŸŒ
GitHub
github.com โ€บ midnite81 โ€บ xml2array
GitHub - midnite81/xml2array: A package to convert XML to an Array with the inbuilt ability to convert to Json, Laravel Collection and Serialize
Run composer install or composer ...xml2array. use Midnite81\Xml2Array\Xml2Array; $xml = Xml2Array::create($someXmlString); // or $xml = (new Xml2Array())->convert($someXmlString); If the string is invalid then an IncorrectFor...
Author ย  midnite81
๐ŸŒ
GitHub
github.com โ€บ mtownsend5512 โ€บ xml-to-array
GitHub - mtownsend5512/xml-to-array: Easily convert valid xml to a php array.
$xml = <<<XML <?xml version="1.0"?> <request> <carrier>fedex</carrier> <id>123</id> <tracking_number>9205590164917312751089</tracking_number> </request> XML; $array = xml_to_array($xml); // $array is: [ 'carrier' => 'fedex', 'id' => '123', ...
Starred by 117 users
Forked by 14 users
Languages ย  PHP 100.0% | PHP 100.0%
Top answer
1 of 16
426

Here is php 5.2 code which will convert array of any depth to xml document:

Array
(
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Pune
                            [zip]=>411006
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Mumbai
                            [zip]=>400906
                        )   
                )

        )
)

generated XML would be as:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Pune</city>
            <zip>411006</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Mumbai</city>
            <zip>400906</zip>
        </address>
    </student>
</student_info>

PHP snippet

<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
    foreach( $data as $key => $value ) {
        if( is_array($value) ) {
            if( is_numeric($key) ){
                $key = 'item'.$key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

// initializing or creating array
$data = array('total_stud' => 500);

// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

// function call to convert array to xml
array_to_xml($data,$xml_data);

//saving generated xml file; 
$result = $xml_data->asXML('/file/path/name.xml');

?>

Documentation on SimpleXMLElement::asXML used in this snippet

2 of 16
227

a short one:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

๐ŸŒ
ItSolutionstuff
itsolutionstuff.com โ€บ post โ€บ how-to-convert-xml-file-to-array-in-phpexample.html
How to Convert XML File to Array in PHP? - ItSolutionstuff.com
May 14, 2024 - In this example, i will give you ... convert xml to array in php. so here, we will keep one simple example file and convert into php array. ... [description] => Light Belgian waffles covered with an assortment of fresh berries and whipped cream ... I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, ...