读取特定文件夹中的所有txt文件,并将所有内容写入一个txt文件 [英] Read all txt files in a specific folder and write all contents in one txt file

查看:409
本文介绍了读取特定文件夹中的所有txt文件,并将所有内容写入一个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从一个文件夹中读取所有*.txt文件,并将每个文件中的所有内容写入另一个txt文件中.但是不知何故,它只将一行写到txt文件中.

I try to read all *.txt files from a folder and write all content from each file into another txt file. But somehow it only writes one line into the txt file.

我尝试使用fwrite()file_put_contents(),但都没有效果.

I tried with fwrite() and file_put_contents(), neither worked.

这是我的代码:

<?php

    $dh = opendir('/Applications/XAMPP/xamppfiles/htdocs/test/');

    while($file = readdir($dh)) {
        $contents = file_get_contents('/Applications/XAMPP/xamppfiles/htdocs/test/' . $file);
        $dc = array($contents);   
    }

    file_put_contents('content.txt', $dc);

?>

推荐答案

这应该对您有用:

(在这里,我使用 glob() 获取目录中的所有* .txt文件 file_get_contents() ,然后使用 file_put_contents() )

(Here I get all *.txt files in a directory with glob(). After this I loop through every file with a foreach loop and get the content of each single file with file_get_contents() and I put the content into the target file with file_put_contents())

<?php

    $files = glob("path/*.txt");
    $output = "result.txt";

    foreach($files as $file) {
        $content = file_get_contents($file);
        file_put_contents($output, $content, FILE_APPEND);
    }

?>

这篇关于读取特定文件夹中的所有txt文件,并将所有内容写入一个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆