如何在php中上传和解析CSV文件

发布于 2024-10-30 21:01:48 字数 61 浏览 1 评论 0原文

我想用 php 上传 csv 文件。文件上传后,我想显示CSV文件的数据。我想要一个如何完成这项任务的例子。

I want to upload a csv file with php. After the file is uploaded, I want to display the data of the CSV file. I would like an example how to accomplish this task.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

不寐倦长更 2024-11-06 21:01:48

现在可以通过更简单的方式完成此操作。

$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));

这将返回一个已解析的 CSV 数据数组。然后您可以使用 foreach 语句循环遍历它。

This can be done in a much simpler manner now.

$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));

This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.

红衣飘飘貌似仙 2024-11-06 21:01:48

未经测试,但应该给你这个想法。视图:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

upload.php 控制器:


$csv = array();

// check there are no errors
if($_FILES['csv']['error'] == 0){
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];

    // check the file is a csv
    if($ext === 'csv'){
        if(($handle = fopen($tmpName, 'r')) !== FALSE) {
            // necessary if a large csv file
            set_time_limit(0);

            $row = 0;

            while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // number of fields in the csv
                $col_count = count($data);

                // get the values from the csv
                $csv[$row]['col1'] = $data[0];
                $csv[$row]['col2'] = $data[1];

                // inc the row
                $row++;
            }
            fclose($handle);
        }
    }
}

untested but should give you the idea. the view:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

upload.php controller:


$csv = array();

// check there are no errors
if($_FILES['csv']['error'] == 0){
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];

    // check the file is a csv
    if($ext === 'csv'){
        if(($handle = fopen($tmpName, 'r')) !== FALSE) {
            // necessary if a large csv file
            set_time_limit(0);

            $row = 0;

            while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // number of fields in the csv
                $col_count = count($data);

                // get the values from the csv
                $csv[$row]['col1'] = $data[0];
                $csv[$row]['col2'] = $data[1];

                // inc the row
                $row++;
            }
            fclose($handle);
        }
    }
}
暗喜 2024-11-06 21:01:48

虽然您可以轻松找到如何使用 php 处理文件上传的教程,并且有处理 CSV 的函数(手册),但我将发布一些代码,因为就在几天前我在做一个项目,其中包括一些您可以使用的代码使用...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

   if ( isset($_FILES["file"])) {

            //if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

        }
        else {
                 //Print file details
             echo "Upload: " . $_FILES["file"]["name"] . "<br />";
             echo "Type: " . $_FILES["file"]["type"] . "<br />";
             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

                 //if file already exists
             if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }
             else {
                    //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
        }
     } else {
             echo "No file selected <br />";
     }
}

我知道一定有一种更简单的方法来做到这一点,但我读取了 CSV 文件并将每条记录的单个单元格存储在二维数组中。

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

    echo "File opened.<br />";

    $firstline = fgets ($file, 4096 );
        //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
    $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

        //save the different fields of the firstline in an array called fields
    $fields = array();
    $fields = explode( ";", $firstline, ($num+1) );

    $line = array();
    $i = 0;

        //CSV: one line is one record and the cells/fields are seperated by ";"
        //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
    while ( $line[$i] = fgets ($file, 4096) ) {

        $dsatz[$i] = array();
        $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

        $i++;
    }

        echo "<table>";
        echo "<tr>";
    for ( $k = 0; $k != ($num+1); $k++ ) {
        echo "<td>" . $fields[$k] . "</td>";
    }
        echo "</tr>";

    foreach ($dsatz as $key => $number) {
                //new table row for every record
        echo "<tr>";
        foreach ($number as $k => $content) {
                        //new table cell for every field of the record
            echo "<td>" . $content . "</td>";
        }
    }

    echo "</table>";
}

所以我希望这会有所帮助,这只是一小段代码,我还没有测试它,因为我使用的它略有不同。评论应该解释一切。

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

   if ( isset($_FILES["file"])) {

            //if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

        }
        else {
                 //Print file details
             echo "Upload: " . $_FILES["file"]["name"] . "<br />";
             echo "Type: " . $_FILES["file"]["type"] . "<br />";
             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

                 //if file already exists
             if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }
             else {
                    //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
        }
     } else {
             echo "No file selected <br />";
     }
}

I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

    echo "File opened.<br />";

    $firstline = fgets ($file, 4096 );
        //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
    $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

        //save the different fields of the firstline in an array called fields
    $fields = array();
    $fields = explode( ";", $firstline, ($num+1) );

    $line = array();
    $i = 0;

        //CSV: one line is one record and the cells/fields are seperated by ";"
        //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
    while ( $line[$i] = fgets ($file, 4096) ) {

        $dsatz[$i] = array();
        $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

        $i++;
    }

        echo "<table>";
        echo "<tr>";
    for ( $k = 0; $k != ($num+1); $k++ ) {
        echo "<td>" . $fields[$k] . "</td>";
    }
        echo "</tr>";

    foreach ($dsatz as $key => $number) {
                //new table row for every record
        echo "<tr>";
        foreach ($number as $k => $content) {
                        //new table cell for every field of the record
            echo "<td>" . $content . "</td>";
        }
    }

    echo "</table>";
}

So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

简单 2024-11-06 21:01:48

我在 @Thomas Clowes 答案的帮助下创建了下面的代码片段

$tmpName = $_FILES['csv']['tmp_name'];

$csv_data = array_map('str_getcsv', file($tmpName));

array_walk($csv_data , function(&$x) use ($csv_data) {
  $x = array_combine($csv_data[0], $x);
});

/** 
*
* array_shift = remove first value of array 
* in csv file header was the first value
* 
*/
array_shift($csv_data);

// Print Result Data
echo '<pre/>';
print_r($csv_data);    

它将得到如下结果

 Array
(
   [0] => Array
    (
        
        [make] => Audi
        [model] => S4
        [grade] => 
        [chassis] => WAUZZZ8K9DA076529
        [year] => 2012
        [kms] => 127000
        [color] => White
        [doors] => 4
        [cc] => 3000
        [engineno] => 
        [trans] => FAT
        [fueltype] => P
        [condition] => 4            
        [price] => 15753
        
    )

)

I have created below snippet with the help of @Thomas Clowes answer

$tmpName = $_FILES['csv']['tmp_name'];

$csv_data = array_map('str_getcsv', file($tmpName));

array_walk($csv_data , function(&$x) use ($csv_data) {
  $x = array_combine($csv_data[0], $x);
});

/** 
*
* array_shift = remove first value of array 
* in csv file header was the first value
* 
*/
array_shift($csv_data);

// Print Result Data
echo '<pre/>';
print_r($csv_data);    

It will get result like below

 Array
(
   [0] => Array
    (
        
        [make] => Audi
        [model] => S4
        [grade] => 
        [chassis] => WAUZZZ8K9DA076529
        [year] => 2012
        [kms] => 127000
        [color] => White
        [doors] => 4
        [cc] => 3000
        [engineno] => 
        [trans] => FAT
        [fueltype] => P
        [condition] => 4            
        [price] => 15753
        
    )

)
何处潇湘 2024-11-06 21:01:48

您需要 PHP 手册中的处理文件上传部分,并且最好查看 fgetcsv() 和explode()。

You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().

狼亦尘 2024-11-06 21:01:48

我觉得 str_getcsv — 将 CSV 字符串解析为数组是您的最佳选择。

  1. 您需要将文件上传到服务器。

  2. 使用 str_getcsv 解析文件。

  3. 遍历数组并根据您的网站需要进行对齐。

I feel str_getcsv — Parse a CSV string into an array is the best option for you.

  1. You need to upload the file to the server.

  2. Parse the file using str_getcsv.

  3. Run through the array and align as per u need on your website.

箜明 2024-11-06 21:01:48
function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }
function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }
初见终念 2024-11-06 21:01:48
public function uploadCsvFile(){
   try{ 
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $request = $this->post();
        $fileName = $request->file;
        $file = fopen($fileName, "r"); //open the file
        // $fileName = $_FILES["file"]["tmp_name"];
        while(($column = fgetcsv($file)) !== FALSE){
            $num = count($column);
            $this->dbw->query("insert into csv_upload(first_name,last_name,email,phone,address,pin) values('".$column[0]."','".$column[1]."','".$column[2]."','".$column[3]."','".$column[4]."','".$column[5]."')");
        }

        fclose($file);
    }
    }catch (Exception $e) {
        $this->responseErr($e->getMessage(), 500);
    }
}
public function uploadCsvFile(){
   try{ 
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $request = $this->post();
        $fileName = $request->file;
        $file = fopen($fileName, "r"); //open the file
        // $fileName = $_FILES["file"]["tmp_name"];
        while(($column = fgetcsv($file)) !== FALSE){
            $num = count($column);
            $this->dbw->query("insert into csv_upload(first_name,last_name,email,phone,address,pin) values('".$column[0]."','".$column[1]."','".$column[2]."','".$column[3]."','".$column[4]."','".$column[5]."')");
        }

        fclose($file);
    }
    }catch (Exception $e) {
        $this->responseErr($e->getMessage(), 500);
    }
}
同尘 2024-11-06 21:01:48

你可以尝试用这个:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

You can try with this:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文