Upload tab delimited txt file using form, then make into PHP arrays?

无人久伴 提交于 2019-12-08 08:43:37

问题


I'm trying parse a tab delemited text file into a set of PHP arrays, and help would be very much appreciated.

The .txt wil look like this (tab delimited not spaces)

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

and so on

I wish the PHP arrays to look like this

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

And I need the .txt file uploaded by a simple html form, e.g.

<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>

Any ideas on the code to place inside form.php?

Many thanks!


回答1:


Consider the content of your text.txt file

FristLineFirstData  FirstLineSecondData FirstLineThirdData
SecondLineFirstData SecondLineSecondData    SecondLineThirdData

Tab separed.

And the script :

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

will return

Array
(
    [0] => Array
        (
            [0] => FristLineFirstData
            [1] => FirstLineSecondData
            [2] => FirstLineThirdData
        )

    [1] => Array
        (
            [0] => SecondLineFirstData
            [1] => SecondLineSecondData
            [2] => SecondLineThirdData
        )

)



回答2:


Below is a barebone solution for your problem:

<?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 --!>
 <?
 }
 ?>

The file data will be all grouped in the same array $data, indexed by the corresponding line number in the file.

See:

  • fgetcsv
  • $_FILES

on the PHP documentation website.



来源:https://stackoverflow.com/questions/13689227/upload-tab-delimited-txt-file-using-form-then-make-into-php-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!