解析上传的CSV文件并将数据存储到数据库 [英] Parsing an uploaded CSV file and storing data to database
问题描述
我想使用php
我有一个csv文件的以下功能。每个文件对应于我的数据库中的一行
I have a csv file. Each file corresponds to a row in my database
有一个html表单,可以让我选择csv文件。
There is a html form that will allow me to choose the csv file.
然后,一旦表单提交,我必须解析csv文件并相应插入数据到数据库
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 ?
推荐答案
读取CSV文件通常可以使用 fgetcsv
函数(取决于您的CSV文件类型,您可能必须指定delimiter,separator,...作为参数)
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 cokumn
// ...
}
fclose($f);
} else {
// error
}
>(未测试,但 fgetcsv 的手册页上的示例应该可以帮助您开始使用)
(Not tested, but example given on the manual page of fgetcsv should help you get started)
当然,您必须获取上传文件的正确路径 - 请参阅 $ _ FILE
超全局,以及有关处理文件上传的部分,有关更多信息
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.
并且,要将数据保存到数据库中,您必须使用适合您的数据库引擎的API - 如果使用MySQL,您应该使用:
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)
这篇关于解析上传的CSV文件并将数据存储到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!