Load XML File into Associative Array in PHP

Here’s a neat bit of code to load an XML file into an associative array in PHP. Note that if an XML field is empty it creates a zero element array for that field (for some reason) so I’m checking for this and catching it.

$xml_obj=simplexml_load_file($filename);
$json=json_encode($xml_obj);
$this->file_contents=json_decode($json,true);
			
foreach ($this->file_contents as $key=>$value)
{
  if (is_array($value))
  {
    $value='';
    $this->file_contents[$key]='';
  }
  echo "field::$key value:: ".$value."<br />";
}		
This entry was posted in php on by .

About markn

Mark is the owner and founder of Timesheets MTS Software, an mISV that develops and markets employee timesheet and time clock software. He's also a mechanical engineer, father of four, and a lifelong lover of gadgets.