Reading .csv file in php

2020-02-10 04:27发布

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

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

标签: php csv
8条回答
姐就是有狂的资本
2楼-- · 2020-02-10 04:43

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.

  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>';
查看更多
Luminary・发光体
3楼-- · 2020-02-10 04:54

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

查看更多
孤傲高冷的网名
4楼-- · 2020-02-10 04:54

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

$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 $values will 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 ).

查看更多
Viruses.
5楼-- · 2020-02-10 04:55
$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

查看更多
一纸荒年 Trace。
6楼-- · 2020-02-10 04:58

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."')
            ");
        }
    }
}
查看更多
家丑人穷心不美
7楼-- · 2020-02-10 05:02

If you're using the composer package manager, you can also rely on 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
查看更多
登录 后发表回答