【问题标题】:Read CSV file in PHP and Validate if its first row contains title and date在 PHP 中读取 CSV 文件并验证其第一行是否包含标题和日期
【发布时间】:2018-10-01 08:07:06
【问题描述】:

我必须使用 php 上传一个 csv 文件。但在上传之前我需要验证两件事。

  1. 如果它的标题是标题和日期(只有列)。

  2. 前两行标题不应相同。

这是预期文件的结构。

Title   Date
"The Forest: Season 1: Episode 1",  "7/7/2018"
"Forgive Us Our Debts", "7/7/2018"
"Mr. Sunshine: Season 1: Episode 1",    "7/7/2018"

到目前为止的代码

$rows   = array_map('str_getcsv', file($_FILES["file"]["tmp_name"]));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }

我在关联数组中有一个 csv 文件,但无法读取第一行。

如何读取带有行索引的 CSV 行?

【问题讨论】:

  • 可能是因为标题不在 CSV 中。第二行看起来像“逗号”分隔,但标题看起来像“制表符”分隔。你能展示你是如何尝试访问标题的吗?
  • @codeneuss,其制表符仅分开。为了使它在这里可读,我添加了逗号。
  • 如果我使用 str_getcsv 将 csv 转换为数组,如何读取第一行

标签: php fgetcsv


【解决方案1】:

str_getcsv 有一个逗号作为默认分隔符。而且您只能转换一行 CSV。如果你想转换整个文件,你应该使用 fgetcsv [https://secure.php.net/manual/en/function.fgetcsv.php]

此代码示例将起作用:

<?php

$csv = "Title\tDate
\"The Forest: Season 1: Episode 1\"\t\"7/7/2018\"
\"Forgive Us Our Debts\",\t\"7/7/2018\"
\"Mr. Sunshine: Season 1: Episode 1\",\t\"7/7/2018\"";

$rows   = array_map(function ($csv){
    return str_getcsv($csv, "\t");
}, explode("\n",$csv));


$header = array_shift($rows);
$result    = array();
foreach($rows as $row) {
   $result[] = array_combine($header,$row);
}

var_dump($result);

【讨论】:

    【解决方案2】:

    试试这个

    $csv = array_map('str_getcsv', file('data.csv'));
    if(isset($csv[0])){    
        if($csv[0][0] != 'Title' || $csv[0][1] != 'Date'){      
            return "Heading(Title and/or Date) is missing.";
        }else{        
            foreach ($csv as $key => $value) {
                //Process further
            }
        }    
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      $file = new SplFileObject("file.csv");
      $file->setFlags(SplFileObject::READ_CSV);
      
      $valid = true;
      foreach ($file as $i => $row) {
      
           if ($i > 1) break;
      
           list($title, $date) = $row;
      
           if ($i === 0 && ($title !== 'Title' || $date !== 'Date')) {
                $valid = false;  
           } else {
                $second_row = $file[2];
      
                if ($title === $second_row[0]) {
                    $valid = false;
                }
           }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 1970-01-01
        • 2011-04-06
        • 2020-01-10
        • 2015-12-02
        相关资源
        最近更新 更多