Iceman512 Posted August 26, 2006 Share Posted August 26, 2006 Hello all,I am working in a directory on my server called [b]'gallery'[/b]. Within the [b]'gallery'[/b] directory, I have a folder called [b]'images'[/b], a text file called [b]'image_list.txt'[/b] and the php file containing my script.I want the script to get a list of all files in the [b]'images'[/b] folder and save the list as [b]'image_list.txt'[/b], with a new entry on each line. [b]For example:[/b][color=red]image1.jpegimage2.jpgimage3.pngimage4.gif[/color]Here is my code so far:[code]<?php$dir=opendir("./images");while($file=readdir($dir)){ if ($file!="." and $file!="..") { if (is_dir($file)) { print "$file (directory)<br>"; } else { print $file."<br />"; } }}closedir($dir);// Start writing the data to the file, 'image_list.txt': $dest = "image_list.txt"; $Handle = fopen($dest, 'w+'); $Data = $file; fwrite($Handle, $Data); fclose($Handle); } } $d->close(); ?>[/code]Experienced coders will probably cringe at my code! I have tried several looping methods, but I can only manage a single entry in the text file at best.Thanks for any help,Iceman Quote Link to comment https://forums.phpfreaks.com/topic/18708-write-data-to-text-file-loop-solved/ Share on other sites More sharing options...
Barand Posted August 26, 2006 Share Posted August 26, 2006 I rearranged your code a little[code]<?php$dir=opendir("./images");$dest = "./images/image_list.txt";$Handle = fopen($dest, 'w'); while($file=readdir($dir)){ if ($file!="." and $file!="..") { if (is_dir($file)) { print "$file (directory)<br>"; } else { print $file."<br />"; fwrite($Handle, $file . "\r\n"); } }}closedir($dir);fclose($Handle);?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/18708-write-data-to-text-file-loop-solved/#findComment-80655 Share on other sites More sharing options...
Iceman512 Posted August 26, 2006 Author Share Posted August 26, 2006 Thank you Barand!Just had to edit a tiny piece and it works like a charm.Here's my tested, working code:[code]<?php$dir=opendir("./images");$dest = "image_list.txt"; $Handle = fopen($dest, 'w'); while($file=readdir($dir)){ if ($file!="." and $file!="..") { if (is_dir($file)) { print "$file (directory)<br>"; } else { print $file."<br />"; fwrite($Handle, $file . "\n"); // Original syntax: fwrite($Handle, $file . "\r\n"); } }}closedir($dir);fclose($Handle);?>[/code]Regards,Iceman Quote Link to comment https://forums.phpfreaks.com/topic/18708-write-data-to-text-file-loop-solved/#findComment-80693 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.