Converting XML to Array with PHP

Today, I would like to share about converting xml data to associated array in PHP. Let’s take a look.

We will need just 4 steps to perform that.

Step 1 : read the xml file and get file contents.

// read xml file
$xmlFile = "sample.xml";
$xmlFileContents = file_get_contents($xmlFile);

Step 2 : convert xml data into xml object.

// Convert XML Data into XML Object
$xmlObject = simplexml_load_string($xmlFileContents);

Step 3 : convert xml object to Associated array

// Convert XML data object to  Array
$json  = json_encode($xmlObject);
$array = json_decode($json, true);	

Step 4 : print the result

// print array
print "<pre>";
print "</pre>";

This is all for now. Hope you enjoy that.

By Asahi




tel. 06-6454-8833(平日 10:00~17:00)