Jump to content

Archived

This topic is now archived and is closed to further replies.

Iceman512

Write data to text file loop (Solved!)

Recommended Posts

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.jpeg
image2.jpg
image3.png
image4.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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.