[英]Parsing an uploaded CSV file and storing data to database
I want the following functionality using php 我想要使用PHP的以下功能
I have a csv file. 我有一个csv文件。 Each file corresponds to a row in my database
每个文件对应于我的数据库中的一行
There is a html form that will allow me to choose the csv file. 有一个html表单,允许我选择csv文件。
Then once the form is submitted, I must parse the csv file and insert data into the db accordingly 然后,一旦提交表单,我必须解析csv文件并相应地将数据插入到数据库中
How do I go about doing this ? 我该怎么做呢?
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) 通常可以使用
fgetcsv
函数读取CSV文件(根据您的CSV文件类型,您可能必须指定分隔符,分隔符,...作为参数)
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) (未经测试,但fgetcsv手册页上给出的示例应该可以帮助您入门)
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. 当然,您必须获得上传文件的正确路径 - 请参阅
$_FILE
超全局,以及有关处理文件上传的部分,了解有关该文件的更多信息。
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 : 而且,要将数据保存到数据库中,您必须使用适合您的数据库引擎的API - 如果使用MySQL,您应该使用:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.