【问题标题】:Upload tab delimited txt file using form, then make into PHP arrays?使用表单上传制表符分隔的txt文件,然后制作成PHP数组?
【发布时间】:2012-11-21 06:31:06
【问题描述】:

我正在尝试将一个制表符分隔的文本文件解析为一组 PHP 数组,非常感谢您的帮助。

.txt 看起来像这样(制表符分隔而不是空格)

data1a data1b data1c data1d
data2a data2b data2c data2d
data3a data3b data3c data3d
data4a data4b data4c data4d

等等

我希望 PHP 数组看起来像这样

$arrayA = array('data1a', 'data2a', 'data3a', 'data4a');
$arrayB = array('data1b', 'data2b', 'data3b', 'data4b');
$arrayC = array('data1c', 'data2c', 'data3c', 'data4c');
$arrayD = array('data1d', 'data2d', 'data3d', 'data4d');

我需要一个简单的html表单上传的.txt文件,例如

<form action="form.php" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" /> 
  <input type="submit" name="submit" value="Submit" />
</form>

对放在 form.php 中的代码有什么想法吗?

非常感谢!

【问题讨论】:

    标签: php arrays file tabs delimited


    【解决方案1】:

    考虑您的text.txt 文件的内容

    FristLineFirstData FirstLineSecondData FirstLineThirdData SecondLineFirstData SecondLineSecondData SecondLineThirdData

    制表符分开。

    还有脚本:

    <?php
    $file = "text.txt";// Your Temp Uploaded file
    $handle = fopen($file, "r"); // Make all conditions to avoid errors
    $read = file_get_contents($file); //read
    $lines = explode("\n", $read);//get
    $i= 0;//initialize
    foreach($lines as $key => $value){
        $cols[$i] = explode("\t", $value);
        $i++;
    }
    echo "<pre>";
    print_r($cols); //explore results
    echo "</pre>";
    ?>
    

    会回来

    大批 ( [0] => 数组 ( [0] => FristLineFirstData [1] => FirstLineSecondData [2] => FirstLineThirdData ) [1] => 数组 ( [0] => SecondLineFirstData [1] => SecondLineSecondData [2] => SecondLineThirdData ) )

    【讨论】:

      【解决方案2】:

      以下是针对您的问题的准系统解决方案:

      <?php
       $error = false;
      
       if (isset($_POST) && isset($_POST['submit']) && isset($_FILES) {)
          $file = $_FILES['file'];
          if (file_exists($_FILES['tmp_name'])){
             $handle = fopen($_FILES['tmp_name']);
             $data = fgetcsv($handle, 0, '\t');
          }
          // do your data processing here
          // ...
          // do your processing result display there
          // ...
          // or redirect to another page.
       }
       if ($error) {
         // put some error message here if necessary
       }
       // form display below
       ?>
       <!-- HTML FORM goes here --!>
       <?
       }
       ?>
      

      文件数据将全部分组在同一个数组$data中,由文件中对应的行号索引。

      见:

      在 PHP 文档网站上。

      【讨论】:

        猜你喜欢
        • 2011-01-17
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多