php - loop through a directory files and run script
32
I have a simple XML parser that i want to run sequentially all files within a directory, my question is how to loop through all xml files and run the script one after another. Instead of doing so manually.
$string = file_get_contents('epgs/file1.xml'); // loop through all files
$xml = new SimpleXMLElement($string);
$events=$xml->xpath("/DVB-EPG/Service/Event");
if ($events) {
foreach ($events as $event) {
$id = $event["id"];
$start_date = $event["start"] ;
$name = $event->ShortEventDescriptor->EventName ;
$text = $event->ShortEventDescriptor->Text;
$values = array (
':event_id'=>$id,
':event_name'=>$name,
':event_desc'=>$text,
':start_date'=>$start_date
);
$stmt = $dbh->prepare ($sql);
$stmt->execute($values);
}
}
Where the directory epgs has multiple files : file1.xml, file2.xml, file3.xml ect..
ANSWER
$files = glob("epgs/*.xml");
foreach ($files as $file) {
//script...
}
Answer
Solution:
Although your question was answered in the comments already, I advise against using
glob()
. You can use SPL iterators instead:Even though the code is much bigger, I still find it more useful. The benefits are as follows:
You get absolute paths, period. With
glob()
that is the case only if your original pattern is absolute as well. That's not very obvious, isn't it?Actually, you get a lot more information that absolute path - you can check file size, its owner etc. Check documentation on SplFileInfo.
The second you find yourself in need of handling recursive pattern, e.g.:
...you'll realize that there's no built-in recursive
glob()
in PHP.glob()
supports many more patterns than simple*
. Unfortunately, they are barely documented:Are you seriously wanting to depend on
libc
implementation that can change for any reason?The patterns
glob()
actually supports seem to be described best on some random blog™:To me, using regular expressions is much more readable. People are much less likely to need to refer to documentation if they see simple regex.