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条回答
We Are One
2楼-- · 2020-02-10 05:04

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);
查看更多
我只想做你的唯一
3楼-- · 2020-02-10 05:05

One liner to parse a CSV file into an array

$csv = array_map('str_getcsv', file('data.csv'));
查看更多
登录 后发表回答