duanlian1960 2010-03-16 11:55
浏览 338
已采纳

解析上传的CSV文件并将数据存储到数据库

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条回答 默认 最新

  • dqpwdai095465 2010-03-16 11:59
    关注

    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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题