开发者

handling csv files fgetcsv & str_getcsv?

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'])) {
    //$filenam开发者_运维知识库e=$_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>";
}
?>


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜