如何允许用户上传多个文本文件,然后将它们保存为字符串并显示它们(在PHP中)?

如何允许用户上传多个文本文件,然后将它们保存为字符串并显示它们(在PHP中)?

问题描述:

I want to allow a user to upload multiple text files using a simple HTML form, and then save them to a string. After that, I want to display them to the user. For example, say I have three text files with the following contents:

file1.txt: this is some text.

file2.txt: this is some more text.

file3.txt: even more text!

When the user uploads them using an HTML form, I want to save them to a string and display them like so:

this is some text.

this is some more text.

even more text!

I have the following (incomplete) code that attempts to get only one file:

    Upload text documents: <br /><br>
    <form action="output.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" size="50" />
    <br />
    <input type="submit" value="Upload File" />
    </form>

    <?php
    $doc = $_POST['file'];
    echo $doc;
    ?>

How can I loop through the files and save them to a string, then display them in the best way possible?

我想允许用户使用简单的HTML表单上传多个文本文件,然后将它们保存为字符串 。 之后,我想将它们显示给用户。 例如,假设我有三个文本文件,其中包含以下内容: p>

file1.txt:这是一些文本。 p>

file2.txt:this 还有一些文字。 p>

file3.txt:更多文字! p>

当用户使用HTML表单上传它们时,我想保存它们 到一个字符串并显示它们: p>

这是一些文本。 p>

这是一些文本。 p>

更多文字! p>

我有以下(不完整)代码尝试只获取一个文件: p>

 上传文本 文件:&lt; br /&gt;&lt; br&gt; 
&lt; form action =“output.php”method =“post”enctype =“multipart / form-data”&gt; 
&lt; input type =“file”  name =“file”size =“50”/&gt; 
&lt; br /&gt; 
&lt; input type =“submit”value =“上传文件”/&gt; 
&lt; / form&gt; 
 \  n&lt;?php 
 $ doc = $ _POST ['file']; 
 echo $ doc; 
?&gt; 
  code>  pre> 
 
 

我如何循环 通过文件并将它们保存为字符串,然后以最佳方式显示它们? p> div>

$filenames = array();

    if(isset($_FILES["documents"]))
    {
       for($i=0; $_FILES['documents']['name'][$i] != '' ; $i++)
       {
           $filenames[$i] = $_FILES['documents']['name'][$i];

           $myfile = fopen("$_FILES['documents']['name'][$i]", "r") or die("Unable to open file!");

           echo fread($myfile,filesize("$_FILES['documents']['name'][$i]"));

           fclose($myfile);

        }

    }

I think this is helps for you!!!!!!!1

use the multiple="multiple"attribute in the input file element.

In completion of White Marcus answer

use the multiple="multiple"attribute in the input file element.

You should have : $_FILES variable, instead of $_POST

<?php

  var_dump($_FILES);

?>

To print a file use file_put_contents()

Best regards

    $filenames = array();

    if(isset($_FILES["documents"]))
    {
       for($i=0; $_FILES['documents']['name'][$i] != '' ; $i++)
       {
           $filenames[$i] = $_FILES['documents']['name'][$i];
        }

    print_r($filename);
    }