dongyi1921 2014-11-04 16:38
浏览 49
已采纳

验证CSV和TXT上的标题

I have a basic import tool that we are using to upload into our database using PHP. Here is a sample script. My question is how can I validate the headers before import? Basically check against a value to make sure the right file is getting imported.I looked everywhere online, but can't seem to find the answer My headers are

SKU, Price, Active

LOAD DATA LOW_PRIORITY LOCAL INFILE '$file' INTO TABLE sample.your_temp_table FIELDS TERMINATED BY ' ' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY ' ' IGNORE 1 LINES //Continue to run rest of script

My question is how to validate the headers before the script is ran? I'm using

$file = $_GET['file']; $file = urldecode ($file); //getting file on upload

  • 写回答

1条回答 默认 最新

  • douyi3632 2014-11-04 17:01
    关注

    I think you will need to read the first line of the $file and compare it to a set list of headers:

    $requiredHeaders = array('SKU', 'Price', 'Active'); //headers we expect
    
    $f = fopen($file, 'r');
    $firstLine = fgets($f); //get first line of csv file
    fclose($f); // close file    
    
    $foundHeaders = str_getcsv(trim($firstLine), ',', '"'); //parse to array
    
    if ($foundHeaders !== $requiredHeaders) {
       echo 'Headers do not match: '.implode(', ', $foundHeaders);
       die();
    }
    
    //run import script…
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站