39

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.

Smi
  • 13,850
  • 9
  • 56
  • 64
Newbie Coder
  • 10,684
  • 19
  • 41
  • 53

8 Answers8

73

From the PHP manual:

<?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);
}
?>
coreyward
  • 77,547
  • 20
  • 137
  • 166
17

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);
?>
Alex
  • 1,223
  • 1
  • 19
  • 31
  • 1
    In what way is it not useful? Seems to me like it works. – greggles Sep 30 '15 at 14:22
  • 1
    I meant that a working example as provided is always more useful than just a point in the right direction. If available of course and correctly written. – Alex Sep 30 '15 at 14:46
15

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

$csv = array_map('str_getcsv', file('data.csv'));
Danijel
  • 12,408
  • 5
  • 38
  • 54
6

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

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • 7
    Could be waaaaaaaaaay easier. Why not a function that takes a CSV string/filename and returns an array or exception? Jeepers why do i have to loop and parse. What is this, the 90s – Jonathan Jan 10 '17 at 02:51
  • 1
    @Jonathan Streaming is far more efficient than loading an entire 40GB CSV file into memory before operating on it. – coreyward Jun 19 '19 at 15:13
2

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);
}
kenorb
  • 155,785
  • 88
  • 678
  • 743
1

If you use composer, you can try CsvFileLoader

luchaninov
  • 6,792
  • 6
  • 60
  • 75
1
$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);
    }
sanjay
  • 219
  • 2
  • 3
0
   $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

Naveed S
  • 5,106
  • 4
  • 34
  • 52