2012-10-07 27 views
1

我一直有问题与PHP - 我非常新的它。主要是使用其他来源的代码片段来做我想做的事情。PHP - 从多个文件中添加数字

无论如何,这是情况。假设我在单独的目录中有4个单独的文本文件。每个文本文件只包含一个数字。我可以在PHP中做什么,将所有这些数字加起来(+)并将输出写入另一个.txt文件?

原始4个文本文档中的数字会定期更新(每2-8秒),因此如果需要指定添加脚本经常更新,那将会非常棒。

感谢, - Kovacic

+3

目前还不清楚[你试过什么](http://stuck.include-once.org/#help9)。找到合适的和不重复的解决方案通常很重要,但是对于研究和努力不明显的问题也是如此。 – hakre

+0

请详细写出问题,因为4个文件中的4个数字对于管理这样的问题并不是一个好的解决方案,如果您可以改为使用数据库,那将会很棒 –

回答

0

你可以做一个

$filename = 'abs/path/to/first/file'; 
$fh = fopen($filename,'r'); 
$firstNumber = fread($fh,filesize($filename)); 
fclose($fh); 

和reapeat所有4个文件

$sum = $firstNumber+$second+$third+$fourth; 
$filename = 'abs/path/tofile'; 
$fh = fopen('abs/path/tofile','w'); 
fwrite($fh,$sum); 
fclose($fh); 

终于把所有的代码在一个无限循环

while(true){ 
    // do some code to calculate some or function call 
    sleep(5); 
} 
+0

语法错误'filename'应该是'$ filename' –

+0

太多重复 – Gordon

1
$sum = 0; 
foreach (array('/path1/1.txt', '/path2/2.txt', '/path3/3.txt', '/path4/4.txt') as $f) 
    $sum += intval(trim(file_get_contents($f))); 

echo $sum, PHP_EOL; 
0

综上所述号码在四个文件,并将其写入到一个新的文件,你可以使用

file_put_contents(
    '/path/to/sum.txt', 
    array_sum(
     array_merge(
      file('/path/to/a/file.txt'), 
      file('/path/to/b/file.txt'), 
      file('/path/to/c/file.txt'), 
      file('/path/to/d/file.txt') 
     ) 
    ) 
); 

不知道你的意思“如果有需要,以指定添加脚本经常更新这样就太好了。”