douxing9228 2015-02-22 06:40
浏览 354
已采纳

读取特定文件夹中的所有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.

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

Here is my code:

<?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);

?>
  • 写回答

2条回答 默认 最新

  • dongmi4734 2015-02-22 06:45
    关注

    This should work for you:

    (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);
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?