Parsing an uploaded CSV file and storing data to database

时光毁灭记忆、已成空白 提交于 2019-12-08 22:30:50

问题


I want the following functionality using php

I have a csv file. Each file corresponds to a row in my database

There is a html form that will allow me to choose the csv file.

Then once the form is submitted, I must parse the csv file and insert data into the db accordingly

How do I go about doing this ?


回答1:


Reading a CSV file can generally be done using the fgetcsv function (depending on your kind of CSV file, you might have to specify the delimiter, separator, ... as parameters)

Which means that going through you file line by line would not be much harder than something like this :

$f = fopen('/path/to/file', 'r');
if ($f) {
    while ($line = fgetcsv($f)) {  // You might need to specify more parameters
        // deal with $line.
        // $line[0] is the first column of the file
        // $line[1] is the second column
        // ...
    }
    fclose($f);
} else {
    // error
}

(Not tested, but example given on the manual page of fgetcsv should help you get started)

Of course, you'll have to get the correct path to the uploaded file -- see the $_FILE superglobal, and the section on Handling file uploads, for more informations about that.

And, to save the data into your database, you'll have to use the API which suits your DB engine -- if using MySQL, you should use either :

  • mysqli
    • Note that you should prefer mysqli, instead of the old mysql extension (which doesn't support features added in MySQL >= 4.1)
  • or PDO


来源:https://stackoverflow.com/questions/2454056/parsing-an-uploaded-csv-file-and-storing-data-to-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!