Reputation: 6316
How can I use PHP to loop through a text file and create file xxx.txt
base of the text of each line?
For example I have a file named files.txt
and it contains
files.txt
red
pink
purple
deep purple
indigo
blue
light blue
cyan
teal
green
I already tried this
<?php
$file = fopen("files.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
$fileName = fgets($file);
$myfile = fopen($fileName.'.txt, "w");
}
fclose($file);
?>
but this only create last green.txt
.
Upvotes: 0
Views: 112
Reputation: 1618
$handle = fopen("path/to/files.txt", "r");
$filesToCreate = [];
if ($handle) {
while (($line = fgets($handle)) !== false) {
// you may need to add the full path here..
$filesToCreate[] = $line . '.txt';
}
fclose($handle);
} else {
// error opening the file.
}
foreach ($filesToCreate as $newFile) {
$createdFile = fopen($newFile, 'w');
fclose($createdFile);
}
Upvotes: 1