PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I have a text file that holds a list of names like so:
john
josh
jason
susan
each on their own line.. and I would like to open this file and count each entry and store that value in a variable, so I could then echo that value to my web page.. thanks
$server_path = $_SERVER['DOCUMENT_ROOT'];
// open the data file
($fp = fopen($server_path."/path/to/datafile/names.txt", 'r')) or die ("Couldn't open the data file");
$count = 0;
// Iterate through each line of the file
while ( ! feof($fp) ) {
$count++;
}
// output the result
echo $count;
<?php
if (FALSE !== ($lines = @file('/path/to/file')))
{
$n_lines = count($lines);
// for large files unset lines array unless you plan
// to use it for something else.
unset($lines);
}
else
{
// failed to open file
$n_lines = 0;
}
echo $n_lines;
?>