如何在 PHP 中导入 csv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5813168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:34:00  来源:igfitidea点击:

How to import csv file in PHP?

phpcsv

提问by Newbie Coder

I am very new to web development. In fact, I am just starting to learn.

我对网络开发很陌生。事实上,我才刚刚开始学习。

Can somebody please give a complete but very simple example on how to import CSV file in PHP? I tried the one I got from the internet but I'm very confused because it's complicated for me. I am using the WAMP server with PHP 5.3.5, Apache 2.2.17, and MySQL 5.5.8. Please help.

有人可以提供一个完整但非常简单的示例,说明如何在 PHP 中导入 CSV 文件吗?我尝试了从互联网上获得的那个,但我很困惑,因为它对我来说很复杂。我将 WAMP 服务器与 PHP 5.3.5、Apache 2.2.17 和 MySQL 5.5.8 一起使用。请帮忙。

I tried to paste the code but it's messy. Honestly, I am also very new to StackOverflow.

我试图粘贴代码,但它很乱。老实说,我对 StackOverflow 也很陌生。

回答by coreyward

From the PHP manual:

从 PHP手册

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

回答by Alex

I know that this has been asked more than three years ago. But the answer accepted is not extremely useful.

我知道三年多前就有人问过这个问题。但是接受的答案并不是非常有用。

The following code is more useful.

下面的代码更有用。

<?php
$File = 'loginevents.csv';

$arrResult  = array();
$handle     = fopen($File, "r");
if(empty($handle) === false) {
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
        $arrResult[] = $data;
    }
    fclose($handle);
}
print_r($arrResult);
?>

回答by Danijel

The simplest way I know ( str_getcsv), it will import a CSV file into an array.

我知道的最简单的方法(str_getcsv),它会将一个 CSV 文件导入到一个数组中。

$csv = array_map('str_getcsv', file('data.csv'));

回答by Jason McCreary

PHP > 5.3 use fgetcsv()or str_getcsv(). Couldn't be simpler.

PHP > 5.3 使用fgetcsv()str_getcsv()。不能更简单。

回答by kenorb

Here is the version to extract the specific columns by name (modified from @coreyward):

这是按名称提取特定列的版本(从@coreyward修改):

$row = 0;
$headers = [];
$filepath = "input.csv";
if (($handle = fopen($filepath, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if (++$row == 1) {
          $headers = array_flip($data); // Get the column names from the header.
          continue;
        } else {
          $col1 = $data[$headers['Col1Name']]; // Read row by the column name.
          $col2 = $data[$headers['Col2Name']];
          print "Row $row: $col1, $col2\n";
        }
    }
    fclose($handle);
}

回答by luchaninov

If you use composer, you can try CsvFileLoader

如果你使用composer,你可以试试CsvFileLoader

回答by sanjay

$row = 1;
    $arrResult  = array();
    if (($handle = fopen("ifsc_code.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            DB::table('banks')->insert(
                array('bank_name' => $data[1], 'ifsc' => $data[2], 'micr' => $data[3], 'branch_name' => $data[4],'address' => $data[5], 'contact' => $data[6], 'city' => $data[7],'district' => $data[8],'state' => $data[9])
            );
        }
        fclose($handle);
    }

回答by Bhupendra Kanojiya

   $filename=mktime().'_'.$_FILES['import']['name'];

      $path='common/csv/'.$filename;

    if(move_uploaded_file($_FILES['import']['tmp_name'],$path))
{

if(mysql_query("load data local infile '".$path."' INTO TABLE tbl_customer FIELDS TERMINATED BY ',' enclosed by '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (`location`, `maildropdate`,`contact_number`,`first_name`,`mname`,`lastname`,`suffix`,`address`,`city`,`state`,`zip`)"))

    {
      echo "imported successfully";

}

echo "<br>"."Uploaded Successfully".$path;

}

look herefor futher info

看看这里获得进一步的信息