PHP, read values from txt file, and add

Discussion in 'Programming/Scripts' started by edge, Jul 3, 2007.

  1. edge

    edge Active Member Moderator

    It's me again, with for some people here probably an easy thing to code.

    I have this txt file, with in it "tags" with a number value that I need to add up all together.

    The parts in the txt file that I need look like this:
    So. The code needs to read the value after <segment bytes=", and add it all together. (it's always on a new line)
    The times that <segment bytes=" is in the file could be one time or many times!

    Now. How could I do this the best way?
    Any help appreciated!
     
  2. Juddling

    Juddling New Member

    Using PHP

    I'm not too sure about the reading bytes part sorry but below is php that will read a file line by line:

    <?php
    $handle = @fopen("/tmp/inputfile.txt", "r");
    if ($handle) {
    while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    echo $buffer;
    }
    fclose($handle);
    }
    ?>

    http://uk.php.net/fgets
     
  3. blu3ness

    blu3ness New Member

    Might be something like this

    Hello, something I wrote very quickly. Could have bugs, havn't tested yet.
    PHP:
    #!usr/local/bin/php

    <?php
    $total 
    0;

    $fin = @fopen("path to file""r");
    if (
    $fin) {

        while (!
    feof($fin)) {
            
    $buffer fgets($fin);
            if (
    preg_match('/<segment bytes="(\d+)"/',$buffer,$matched))
                
    $total += $matched['1'];
            else
                continue;
            }
        
    fclose($fin);
        print 
    $total;

    }
    ?> 
     
  4. edge

    edge Active Member Moderator

    Hi blu3ness,

    This looks good! I'll give it a try later today.

    Thank you
     

Share This Page