在 php 中读取 .csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5455872/
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 21:30:06  来源:igfitidea点击:

Reading .csv file in php

phpcsv

提问by Neha Raje

I want to read .csv file in PHP and put its contents into the database. I wrote the following code:

我想在 PHP 中读取 .csv 文件并将其内容放入数据库中。我写了以下代码:

$row = 1;
$file = fopen("qryWebsite.csv", "r");
while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "\n";}}
fclose($file);

I do not get any error but it does not show me result.

我没有收到任何错误,但它没有显示我的结果。

回答by Shameer

I am using parseCSVclass to read data from csv files. It can give more flexibility in reading csv file.

我正在使用parseCSV类从 csv 文件中读取数据。它可以在读取 csv 文件时提供更大的灵活性。

回答by Michael Trachsel

this is not tested... but something like this should do the trick:

这没有经过测试......但是这样的事情应该可以解决问题:

$row = 1;
if (($handle = fopen("xxxxxxxxx.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++) {
            $blackpowder = $data;
            $dynamit = implode(";", $blackpowder);
            $pieces = explode(";", $dynamit);
            $col1 = $pieces[0];
            $col2 = $pieces[1];
            $col3 = $pieces[2];
            $col4 = $pieces[3];
            $col5 = $pieces[5];
            mysql_query("
                INSERT INTO `xxxxxx` 
                    (`xxx`,`xxx`,`xxx`,`xxxx`,`xxx`) 
                VALUES 
                    ('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."')
            ");
        }
    }
}

回答by Sumith Harshan

$fp = fopen('ReadMe.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp,1024)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.$csv_line[$i].'</td>';
    }
    print "</tr>\n";
}
print '</table>';
fclose($fp) or die("can't close file");

More Details

更多细节

回答by Deenadhayalan Manoharan

Try this....

尝试这个....

In PHP it is often useful to be able to read a CSV file and access it's data. That is where the fgetcsv() function comes in handy, it will read each line of a CSV file and assign each value into an ARRAY. You can define the separator in the function as well see PHP docs for fgetcsv()for more options and examples.

在 PHP 中,能够读取 CSV 文件并访问其数据通常很有用。这就是 fgetcsv() 函数派上用场的地方,它将读取 CSV 文件的每一行并将每个值分配到一个数组中。您可以在函数中定义分隔符,也可以查看fgetcsv() 的PHP 文档以获取更多选项和示例。

  function readCSV($csvFile){
        $file_handle = fopen($csvFile, 'r');
        while (!feof($file_handle) ) {
            $line_of_text[] = fgetcsv($file_handle, 1024);
        }
        fclose($file_handle);
        return $line_of_text;
    }


    // Set path to CSV file
    $csvFile = 'test.csv';

    $csv = readCSV($csvFile);
    echo '<pre>';
    print_r($csv);
    echo '</pre>';

回答by Danijel

One liner to parse a CSV file into an array by using str_getcsv.

一个使用str_getcsv将 CSV 文件解析为数组的衬垫

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

To build a database query that will import all the values into database at once:

要构建一个将所有值一次导入数据库的数据库查询:

$query = 
    "INSERT INTO tbl_name (a,b,c) VALUES " .
    implode( ',', array_map( function( $params ) use ( &$values ) {
        $values = array_merge( (array) $values, $params );
        return '(' . implode( ',', array_fill( 0, count( $params ), '?' ) ) . ')';
    }, $csv ) );

This will build a prepared statement with question mark placeholders, like:

这将构建一个带有问号占位符的准备好的语句,例如:

INSERT INTO tbl_name (a,b,c) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?)

, and variable $valueswill be one-dimensional array that holds values for the statement. One caveat here is that csv file should contain less than 65,536 entries ( maximum number of placeholders ).

, 变量$values将是保存语句值的一维数组。这里的一个警告是 csv 文件应包含少于 65,536 个条目(占位符的最大数量)。

回答by Jayni

One liner to parse a CSV file into an array

一个将 CSV 文件解析为数组的衬垫

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

回答by Andreas

If you're using the composer package manager, you can also rely on league/csv

如果您使用的是composer 包管理器,您还可以依赖league/csv

According to theire documentation:

根据他们的文档

use League\Csv\Reader;

//load the CSV document from a file path
$csv = Reader::createFromPath('/path/to/your/csv/file.csv', 'r');
$csv->setHeaderOffset(0);

$header = $csv->getHeader(); //returns the CSV header record
$records = $csv->getRecords(); //returns all the CSV records as an Iterator object

回答by vijayrana

You can try the below code. It works perfect for me. I have comment to make it more understandable. You can take reference from this code.

你可以试试下面的代码。它非常适合我。我有评论以使其更容易理解。您可以参考此代码。

<?php

//display error message if any
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

//openup connection to database
include('dbconnection.php');

//open csv file
if (($handle = fopen("files/cities.csv", "r")) !== FALSE) {

    $flag = true;
    $id=1;

    //fetch data from each row
    while (($data = fgetcsv($handle, ",")) !== FALSE) {
        if ($flag) {
            $flag = false;
            continue;
        }

        //get data from each column
        $city_id      = $data[0];
        $country_name = $data[1];
        $city_name    = $data[2];
        $state_code   = $data[3];

        //query to insert to database
        $sql = "INSERT IGNORE INTO `DB_Name`.`cities` 
                (`id`,`city_id`, country_name`, `city_name`,`state_code`)
                VALUES 
                ('$id','$city_id','$country_name','$city_name','$state_code')";

        echo $sql;

        //execute the insertion query
        $retval = mysql_query($sql, $conn);

        if($retval == false )
        {
          die('Could not enter data: ' . mysql_error());
        }

        echo "<p style='color: green;'>Entered data having id = " .$id. " successfully</p><br>";
        $id++;
    }

    echo "<br><p style='color: orange;'>Congratulation all data successfully inserted</p>";

    fclose($handle);
}

//close the connection
mysql_close($conn);