Hi Guys,

Im just starting out with PHP and im trying to write a script which will count the number of lines in a given text file. I figure ill have to use fopen to open the text file, but where from there. I guess I could make each of the lines part of an array (not sure of the code) and count it that way but theres probably an easier way. I figure this whole script could be done in about 5lines, can someone please help me out?

Thanks a lot,

Stewart

    <?php
    $fileName = "/path/to/file.txt";
    $fp = fopen ($fileName, "r");
    while(!feof($fp)) {
    $lines[] = fgets($fp, 4096);

    gets each line or a 4k chunk from file,

    whichever comes first. (And 4096 chars should

    be longer than most lines of text.)

    }
    $count = count($lines);

    echo "There are $count lines in $fileName";
    ?>

      I am new to this as well, but I was trying to do something similar to what you are doing at one point.

      If you are wanting to count the rows, the file needs to read into an array. The fopen() function opens a stream (I believe). Use the file() function, it will open the file into an array and then use the count() function to return the number of rows.

      <?php
      $filename="myfile.txt";
      $numrows=count(file($filename));
      ?>

      I hope that at least sends you in the right direction. I am learning right now too. 😉

      EDIT: Doh! Beaten down... Hehehe...

        Thanks a lot for your help, the contribution is much appreciated. hismightiness: well you can have the prize for less lines, assuming your script actually works. Im at work at the moment so cant test just yet! 🙂

          Originally posted by hismightiness

          <?php
          $filename="myfile.txt";
          $numrows=count(file($filename));
          ?>

          this will work but it is a highly inefficient solution if you need to do anyting else with the file because you'll have to read the file twice. If you are not doing any other processing of the file then this is fine, but I am left wondering why you would need the lines and no other processing of the file. Here is how I would change it.

          Originally posted by hismightiness

          <?php
          function getFileAndLines($filename) {
              if(!file_exists($filename)) {
                  die("dude you can't get a file that's not there.");
              }
              $lines = file($filename);
              array_push($lines,count($lines));
              return $lines
          } //end getFileAndLines
          ?>

          but after writting this it seems a bit over kill to add the lines into the array and count will give that to you when ever you want. The only thing I was commenting on was only read the file once in a script.

            not too interested in doing anything else with the data, at the moment. Using the script just for statistical purposes...

              Write a Reply...