Skip to content

Instantly share code, notes, and snippets.

@igoralves1
Last active April 21, 2016 14:12
Show Gist options
  • Save igoralves1/82b7ff09632fcb9916a31842533f6bf6 to your computer and use it in GitHub Desktop.
Save igoralves1/82b7ff09632fcb9916a31842533f6bf6 to your computer and use it in GitHub Desktop.
PHP - Read xml and return a php array. Deal with date formating.
/*
This function goes to the directory $pathDir, pass trough each all files inside it,
seeks for any file that math to the $searchString and reads it.
Return the content of all matched xml files within a php Array.
Ex:
We have inside the FTP the follow files genereted by a CronJob:
fileCarAudiRent2015.xml, fileCarAudiRent2016.xml, fileCarAudiSell2015.xm,
fileCarBMWRent2015.xml, fileCarBMWSell2016.xml, fileBoatWMBRent2015.xml, fileBoatWMBSell2015.xml,
fileBoatAudiRent2015.xml, fileBoatAudiSell2016.xml, ... .
We want to grab the content of all files that matches "Boat" string.
So, we need to do like this:
$arrInfo = read_XML_from_Folder_return_arrayAll("c:/Path_to_the_Folder","Boat");
We want to grab the content of all files that matches "Sell2015" string.
So, we need to do like this:
$arrInfo = read_XML_from_Folder_return_arrayAll("c:/Path_to_the_Folder","Sell2015");
We should inprove this function to match criteria like:
Give me all that has Sell AND 2015
Give me all that has Sell OR 2015
Give me all that has BMW AND 2015
...
*/
public function read_XML_from_Folder_return_arrayAll($pathDir,$searchString) {
$xml_array="";
$dir = new DirectoryIterator($pathDir); //http://php.net/manual/en/class.directoryiterator.php
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile()) {
$fileName = $fileinfo->getFilename();
//Macth rule
$pos = strpos($fileName, $searchString);
if ( $pos!== false) {//If match the sought string
$filePath = $pathDir.$fileName;
$xml = simplexml_load_file($filePath);
$xml_array [] = unserialize(serialize(json_decode(json_encode((array) $xml), 1)));
/* If needed
$invoice_date = $xml_array["Documents"]["InvoiceDate"];
$date = DateTime::createFromFormat('dmY', $invoice_date);//Formated date inside xml
$year = $date->format('Y');//Desired output year
$month = $date->format('M');//Desired output month
*/
}//End of if ( $pos!== false)
}
}
//Testing
echo "<pre>";
print_r($xml_array);
echo "</pre>";
return $xml_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment