Reputation: 353
Trying to figure out a read a directory of php files and write to another file. It works fine except that the first file is being put last in the file.
Can someone help point me in the right direction to modify my code to put the file names in the proper order? The file name will be different at times but I'm hoping to keep them in the same order they are in the directory.
Thanks Bob
<?php
$dirDestination = "build";
$path = "build/combine";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$myfile = fopen("$dirDestination/iframe.php", "a") or die("Unable to open iframe.php file!");
$txt = "<iframe src =\"$file\" width=\"780\" height=\"1100\"> </iframe>\n";
fwrite($myfile, $txt);
fclose($myfile);
}
closedir($handle);
echo "Build completed....";
}
?>
It keeps putting the first file last
<iframe src ="item2.php" width="780" height="1100"> </iframe>
<iframe src ="item3.php" width="780" height="1100"> </iframe>
<iframe src ="item4.php" width="780" height="1100"> </iframe>
<iframe src ="item1.php" width="780" height="1100"> </iframe>
Upvotes: 0
Views: 124
Reputation:
Data structures are your friend. So, instead of readdir()
try using scandir()
to get an array of filenames.Then loop through this array to generate a second array of iframe
strings. Then implode
this second array and fwrite
the resultant string.
Here's what it might look like:
<?php
$dirDestination = "build";
$path = "build/combine";
$txt_ary = array();
$dir_ary = scandir($path);
foreach ($dir_ary as $file) {
if ($file === '.' || $file === '..') continue;
$txt_ary[] = "<iframe src =\"$file\" width=\"780\" height=\"1100\"> </iframe>\n";
}
$myfile = fopen("$dirDestination/iframe.php", "a") or die("Unable to open iframe.php file!");
fwrite($myfile, implode($txt_ary));
fclose($myfile);
echo "Build completed....";
?>
I tested this and got the desired ordering.
Upvotes: 1
Reputation: 6565
Actually i dont know why it sorts it that way. But you could try glob for this.
$files = glob("mypath/*.*");
As long as you dont pass GLOB_NOSORT as second param, result will be sorted. But the sortfunction still sort numbers wrong.
1
10
2
3
But in your case you dont seem to have this problem.
With GLOB_BRACE you can also search for special endings like {jpg|png|gif}
. And you propably save some lines of code too. And instead of a while
it would be a foreach
.
Upvotes: 0