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

北战南征 提交于 2019-12-07 02:05:32

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
        )

)

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:

on the PHP documentation website.

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