Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling csv files fgetcsv & str_getcsv?

Tags:

php

I have a three part question is fgetcsv better than str_getcsv and is there a way to only allow .csv file types to be displayed in the file upload dialog? Last should I/do I need to use ini_set('auto_detect_line_endings', true);

<?php
if (isset($_POST['submit'])) {
    //$filename=$_POST['filename'];
    $filename = file_get_contents($_FILES['uploadedfile']['tmp_name']);
    $handle = fopen("$filename", "r");
    while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {

        $import = "INSERT into kmmb_member1(no_ahli,no_pin,nama,no_ic_baru,no_ic_lama) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
        mysql_query($import) or die(mysql_error());
    }
    fclose($handle);
    print "Import done";
} else {

    print "<form action='import.php' method='post'>";
    print "Type file name to import:<br />";
    // print "<input type='text' name='filename' size='20' /><br />";
    print "Select csv file: <input name='uploadedfile' type='file' /><br />";
    print "<input type='submit' name='submit' value='submit' /></form>";
}
?>
like image 260
acctman Avatar asked Nov 25 '10 05:11

acctman


People also ask

What is Fgetcsv?

The fgetcsv() function parses a line from an open file, checking for CSV fields.

How do I read a CSV file in column wise in php?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==

What is CSV file in php?

CSV (Comma Separated Values) is a very popular import and export data format used in spreadsheets and databases. Each line in a CSV file is a data record. Each record consists of one or more fields, separated by commas.


1 Answers

Is fgetcsv() better than str_getcsv()?

Yes, when opening from a file. Use str_getcsv() only when you have the CSV already as a string in your program.

Is there a way to only allow .csv file types to be displayed in the file upload dialog?

No, unless you use a Flash wrapper. However, you can detect the file extension with JavaScript, and you must accept only .csv with PHP (use pathinfo($filename, PATHINFO_EXTENSION)).

However, ensuring it has .csv does not confirm it is actually a CSV file.

Should I/do I need to use ini_set('auto_detect_line_endings', true);

No, unless it is not working. The docs state there is a small performance penalty in using it. So only use it when it is required. It is also off by default. Best to leave less common things in php.ini to their default, I have found.

Though make sure magic_quotes and register_globals are always off :)

like image 68
alex Avatar answered Sep 25 '22 16:09

alex