?> Extracting data from XML file stored on a server

Extracting data from XML file stored on a server

You may have XML files stored on you your server that you require data from. These XML files could come from exports from a system or just be maually uploaded. In this example we will look at retrieving the data within multiple XML files and manipulate the retrieved data, in this case storing it within a database.

  	$dir = "www.example.com/xmlfiles ";

if(opendir($dir)){
$files = glob("/xmlfiles/*.xml");
if(isset($files) && count($files) > 0) {
foreach($files as $xmlfile){
$xml = file_get_contents($xmlfile); // get contents of xml, reads the contents of the file into a string

file_put_contents($xmlfile, $xml); // writes the string to the file
$xml = simplexml_load_file($xmlfile); //Convert XML file into a SimpleXMLElement object, output keys and elements of object

if($xml) {
if(!empty($xml->Id)){
$id = $xml->Id; // storing data from xml element in varibale
$firstname = $xml->firstName;
$surname = $xml->surname;
$age = $xml->age;
$jobTitle = $xml->job;
$salary = $xml->salary;

$query = "INSERT INTO table (id, firstanme, surname, age, job, salary)
VALUES ('$id', '$firstname', '$surname', '$age', '$jobTitle', '$salary')";
mysqli_query($conn, $query);
}
unlink($xmlfile); // deletes file when finished
}
}
}
}

Let's break down the above code and analyse what is happening.

The opendir() function opens the directory where the XML files are stored and reads its contents. The glob() function returns an array of the filesnames. In this case we have specified all file names ending in '.xml' within xmlfiles directory.


We then use a for loop to loop through each XML file and use file_get_contents() to read the contents of the XML into a string. file_put_contents() writes the string back to the xml file.


We use simplexml_load_file() to convert the XML file into a SimpleXMLElement object, which allows us to get the keys and elements of each XML object. Now we are able get the data from each XML ojbect and store in a varible. Now you can use the data captured however you require. Here we are simply storing it within a database.


Finally we have used unlink() to delete the XML file from the server once we have stored the data within the database.

Top