I have a .txt file on my server that contains about 30 lines of distinct numbers. This file is overwritten each day and I would like to create a script that adds all the numbers in the text file and writes the total to a new txt file each day. I'm sure this is pretty simple and would greatly appreciate someone sending me a sample script.
Below is an example of the contents of the text file. There is nothing but text in the file.
45
63
54
23
45
Thanks in advance.
add numbers in a list in a txt file
Moderator: General Moderators
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: add numbers in a list in a txt file
Indeed it is pretty straight forward. Simply load file into array, sum the values, and write to a new text file?
.. and then fopen() + fwrite() or file_put_contents()
Code: Select all
$sum = array_sum(file('/path/to/file.txt'));Re: add numbers in a list in a txt file
Thanks for your help. I have got the code to work but am not sure how to write to a new txt file. Here's what I've got so far.
<?php
$lines = file('textfile.txt/');
echo "sum($lines) = " . array_sum($lines) . "\n";
?>
I tried to use "put_file_contents" but either I messed it up or possibly this doesnt work with php4???
Can you help with this?
<?php
$lines = file('textfile.txt/');
echo "sum($lines) = " . array_sum($lines) . "\n";
?>
I tried to use "put_file_contents" but either I messed it up or possibly this doesnt work with php4???
Can you help with this?
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: add numbers in a list in a txt file
Indeed file_put_contents() is php5 only. Take a look at the fopen() and fwrite() in my last post as a php4 alternative. They have a ton of examples 
Re: add numbers in a list in a txt file
Thanks again.
To say Im a newbie is being generous. I understand fopen and fwrite and used them in a basic open & write script but Im not sure how to associate the commands with this script. Can you help, AGAIN.
Thanks a bunch
To say Im a newbie is being generous. I understand fopen and fwrite and used them in a basic open & write script but Im not sure how to associate the commands with this script. Can you help, AGAIN.
Thanks a bunch
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: add numbers in a list in a txt file
I have no problem helping you. All I ask is you try first, then ask questions later. There are a million examples on those two links I gave you (dont forget to user the user comments as well). Give a couple of them a try and post back your results and/or errors that you have questions about.
Good luck.
Good luck.