Jump to content


Photo

Write data to text file loop (Solved!)


  • Please log in to reply
2 replies to this topic

#1 Iceman512

Iceman512
  • Members
  • PipPipPip
  • Advanced Member
  • 81 posts

Posted 26 August 2006 - 09:51 AM

Hello all,

I am working in a directory on my server called 'gallery'. Within the 'gallery' directory, I have a folder called 'images', a text file called 'image_list.txt' and the php file containing my script.

I want the script to get a list of all files in the 'images' folder and save the list as 'image_list.txt', with a new entry on each line.

For example:
image1.jpeg
image2.jpg
image3.png
image4.gif

Here is my code so far:
<?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(); 
?>

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


#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 26 August 2006 - 10:17 AM

I rearranged your code a little

<?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);

?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 Iceman512

Iceman512
  • Members
  • PipPipPip
  • Advanced Member
  • 81 posts

Posted 26 August 2006 - 12:41 PM

Thank you Barand!

Just had to edit a tiny piece and it works like a charm.
Here's my tested, working 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);
?>

Regards,
Iceman





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users