打开文件并写入其他文件

时间:2014-06-13 14:39:27

标签: php file fwrite

我需要文件并将其内容写入其他文件。任何想法怎么做?

我尝试了以下操作,但它无法正常工作,输出仅来自1个文件而非全部

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
  $opn = fopen($file, "r");
  $rad = fread($opn, 1024000);
  fclose($opn);
  $opn = fopen('output.txt', 'a');
  fwrite($opn, $rad);
  fclose($opn);
}

5 个答案:

答案 0 :(得分:1)

您可以使用file_get_contents()获取文件内容,并使用file_put_contents()将内容保存在其他文件中 所以你可以把它放在你的循环中

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
   // Open the file to get existing content
   $content = file_get_contents($file);
   // Write the contents to the new file
   file_put_contents('new_'.$file, $content);
}

如果要合并所有文件内容并将它们放在一个文件中,可以将其更改为

$files = glob('texts/*.txt', GLOB_BRACE);
$content = ''
foreach($files as $file){
   // Open the file to get existing content
   $content. = file_get_contents($file);
}
// Write the contents to the new file
file_put_contents('output.txt', $content);

答案 1 :(得分:0)

如果您正在使用php5或以上使用File_put_contents并将其循环

e.g。

 int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

答案 2 :(得分:0)

我对此不太确定(知道你是否在这方面遇到错误会很有趣)但输出文件的发布时间可能不够快,无法重新打开它来自第二次迭代...

尝试这样的事情,看看它是否有效:

$files = glob('texts/*.txt', GLOB_BRACE);
$output = fopen('output.txt', 'a');
foreach($files as $file){
    $opn = fopen($file, "r");
    $rad = fread($opn, 1024000);
    fclose($opn);
    fwrite($output, $rad);
}
fclose($output);

答案 3 :(得分:0)

如果您具有执行权限,则可以更快(如果您使用的是Linux):

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
    exec("cat $file >> output.txt");
}

没有循环:

exec("cat texts/*.txt >> output.txt");

答案 4 :(得分:0)

我解决了这个问题:

$filesss = fopen('output.txt', 'a');
if ($handle = opendir('./texts/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $obsah = file_get_contents('./texts/'.$entry);
            fwrite($filesss, $entry.$obsah.'
');
        }
    }
    closedir($handle);
}
fclose($filesss);

不是最佳解决方案,但对我而言。 Thansk:)