[php] How to import csv file in PHP?

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.

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

This question is related to php csv

The answer is


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);
?>

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

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

   $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 here for futher info


Here is the version to extract the specific columns by name (modified from @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);
}

If you use composer, you can try CsvFileLoader


$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);
    }

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