HowtoForge Forums | HowtoForge - Linux Howtos and Tutorials

HowtoForge Forums | HowtoForge - Linux Howtos and Tutorials (http://www.howtoforge.com/forums/index.php)
-   Programming/Scripts (http://www.howtoforge.com/forums/forumdisplay.php?f=7)
-   -   PHP, read values from txt file, and add (http://www.howtoforge.com/forums/showthread.php?t=13828)

edge 4th July 2007 00:30

PHP, read values from txt file, and add
 
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:
Quote:

text text text
<segment bytes="100" number="1">some random text</segment>
text random text random text
some more random text
<segment bytes="3397" number="1">some random text</segment>
some other random text
<segment bytes="3521" number="1">some random text</segment>
<segment bytes="261" number="2">some random text</segment>
<segment bytes="9621" number="3">some random text</segment>
some more random text
some more random text
<segment bytes="7" number="1">some text</segment>
even more text
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!

Juddling 21st July 2007 23:24

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

blu3ness 4th August 2007 10:38

Might be something like this
 
Hello, something I wrote very quickly. Could have bugs, havn't tested yet.
PHP Code:

#!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;

}
?>


edge 4th August 2007 11:01

Quote:

Originally Posted by blu3ness
Hello, something I wrote very quickly. Could have bugs, havn't tested yet.
PHP Code:

#!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;

}
?>


Hi blu3ness,

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

Thank you


All times are GMT +2. The time now is 11:49.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.