trauch Posted December 20, 2008 Share Posted December 20, 2008 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. Link to comment https://forums.phpfreaks.com/topic/137779-adding-text-and-writing-to-a-new-file/ Share on other sites More sharing options...
trq Posted December 20, 2008 Share Posted December 20, 2008 $total = 0; foreach (file('textfile.txt') as $line) { $total += $line; } put_file_contents('total.txt', $total); Link to comment https://forums.phpfreaks.com/topic/137779-adding-text-and-writing-to-a-new-file/#findComment-720126 Share on other sites More sharing options...
trauch Posted December 20, 2008 Author Share Posted December 20, 2008 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? Link to comment https://forums.phpfreaks.com/topic/137779-adding-text-and-writing-to-a-new-file/#findComment-720441 Share on other sites More sharing options...
trauch Posted December 20, 2008 Author Share Posted December 20, 2008 It turns out that file_put_contents is only php5 so Im a bit stuck. 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 Link to comment https://forums.phpfreaks.com/topic/137779-adding-text-and-writing-to-a-new-file/#findComment-720455 Share on other sites More sharing options...
Mark Baker Posted December 20, 2008 Share Posted December 20, 2008 $lines = file('textfile.txt'); $sum = array_sum($lines); $fp = fopen('resultfile.txt', 'w'); fwrite($fp, $sum); fclose($fp); Link to comment https://forums.phpfreaks.com/topic/137779-adding-text-and-writing-to-a-new-file/#findComment-720459 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.