Jump to content

read from a directory write to a file


cabaldemon

Recommended Posts

i have a code that reads from a directory and echose the directory out to the php web page.what it wont do  is write to a file so that a music player or my other a video player can read from

this code is to write to the file

// directory path can be either absolute or relative
$dirPath = 'music/.';
$myFile = "music.m3u"; 
$stringData = "$file"; 
// open the specified directory and check if it's opened successfully 
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end 
while (false !== ($file = readdir($handle))) 

// just skip the reference to current and parent directory 
if ($file != "." && $file != "..") {
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it? 
$fh = fopen($myFile, 'w') or die("can't open file"); 
fwrite($fh, $stringData); 
fclose($fh); 
}

}
// ALWAYS remember to close what you opened 
closedir($handle);
}
?>

 

can anyone help  thank you

Link to comment
https://forums.phpfreaks.com/topic/90569-read-from-a-directory-write-to-a-file/
Share on other sites

Firstly, your opening the file within a loop, not good. Secondly, your opening it in write only mode so it will not append each line. And third and finally, the $stringData variable your trying to write to the file contains nothing. Try...

 

<?php

$dirPath = 'music/';
$myFile = "music.m3u";

$fh = fopen($myFile, 'a') or die("can't open file");

if ($handle = opendir($dirPath)) {
  while (false !== ($file = readdir($handle)))  
    if ($file != "." && $file != "..") {
      if (is_dir("$dirPath/$file")) {
        fwrite($fh, "$dirPath/$file\n");
      }
    }
  } 
}

fclose($fh);
closedir($handle);

?>

Archived

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

×
×
  • Create New...

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.