I’m trying to make a little script to manipulate a txt file with a given directory file contents. What happens is that the text file generated by going to Win command line and execute “dir > file.txt” has lines that are junk to this purpous… like the first 7 lines and last 3. These ones:
O volume na unidade C nao tem nome.
O numero de serie do volume - F879-0704
Directorio de C:\xampp\htdocs\projectX\images\
06-01-2012 14:56 <DIR> .
06-01-2012 14:56 <DIR> ..
.
.
.
140 ficheiro(s) 5.676.057 bytes
2 dir(s) 307.888.893.952 bytes livres
The code I have so far is this:
$file = $_GET['file'];
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$end = 0;
$i = 0;
while($end != 1) {
$output = str_replace("\t|\t", " | ", $data);
$output = explode("\n", $output);
foreach($output as $var) {
if($i > 7){
$newstring = substr($var, 36);
echo "File: " . $newstring . "<br />";
}
$i++;
}
echo "<br /><strong>End of file list!</strong>";
$end = 1;
}
My Question: How can I get this foreach cycle to ignore the last lines of the text file too ?
You should probably use
scandir()or equivalent PHP functions that are specifically made for this.If you insist, however, you can either slice up the array using
array_slice(). The following will remove the two first and last lines.Alternatively, you could just iterate over the part you want with a
forloop instead of aforeachloop.