PHP 动态创建 CSV:跳过 CSV 文件的第一行

33

我正在尝试导入一个CSV文件。 由于我们使用的程序,第一行基本上是所有标题,我希望跳过它们,因为我已经通过HTML输入了自己的标题。 如何让代码跳过CSV的第一行? (strpos命令是为了在所有行中截断第一个字段。)

<?php
$row = 1;
if (($handle = fopen("ptt.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
           $row++;
    for ($c=0; $c < $num; $c++) {
    if(strpos($data[$c], 'Finished') !== false) {
    $c++;
echo "<TR> <TD nowrap>" . $data[$c] . "</ TD>"; }
    Else{
        echo "<TD nowrap>" .  $data[$c] . "</ TD>";
        }
    }
}
fclose($handle);
}
?>
9个回答

74

与其使用if语句来检查是否为第一行,更好的解决方案是在while循环开始的那一行代码之前添加一行额外的代码,如下所示:

....
.....
fgetcsv($handle);//Adding this line will skip the reading of th first line from the csv file and the reading process will begin from the second line onwards
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
.......
.......

它就是这么简单......


6
@dkar,fgetcsv 函数解析第一行(表头),并返回包含这些列的数组。隐式地,文件指针现在位于第二行。 - Eduard
这个答案帮了我很多。我的代码是根据文件头部的第0行、第5行或第6行来创建的,它是动态的。使用这种方法,每当我需要找到所需的头部时,我就可以动态地迭代文件。谢谢。 - Rodolfo Velasco

33

由于您已经在跟踪行号,因此可以使用 continue 跳过第一行循环的其余部分。

例如,在 while 循环的开头添加以下内容(就在 $num = count($data) 上面):

if($row == 1){ $row++; continue; }

还有其他方法可以做到这一点,但请确保在继续操作时,$row仍然被递增,否则您将会得到一个无限循环!


3
请使用以下代码行。
$flag = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
//your code for insert
}

将标志变量设置为true,并将其设置为false,将跳过CSV文件的第一行。这很简单易行。


2
将以下代码放在 while 循环中: if ($row == 1) continue; 该代码会跳过第一行的数据。

0

这个对我有用:

$count = 0;

while(! feof($file))

      {

          $entry = fgetcsv($file, 0, ';');

          if ($count > 0) {
          //skip first line, header


          }

      $count++;
}

0
$count = 0;
while (($fields = fgetcsv($handle, 0, ",")) !== FALSE) {
    $count++;
    if ($count == 1) { continue; }

0
在文件打开语句和 while 循环开始之间增加一个额外的读取操作是最简单的方法,但如果文件没有标题记录,你将会丢失第一条记录。

你的回答可以通过提供更多支持性的信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的回答是否正确。你可以在帮助中心找到更多关于如何撰写好的回答的信息。 - undefined

0
将以下内容添加到上面的$row++;代码的while循环体中:
if ($row == 1) {
    continue;
}

-2

use this code

// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';

if (isset($_FILES['file']))
{   

// get the csv file and open it up
$file = $_FILES['file']['tmp_name'];
//$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). 
$handle = fopen($file, "r"); 
    try { 
    // Database Connection using PDO
    $dbh = new PDO("mysql:host=$hostname;dbname=clasdb", $username, $password);
    // prepare for insertion
    $STM = $dbh->prepare('INSERT INTO statstrackertemp (ServerName, HiMemUti, AvgMemUti, HiCpuUti, AvgCpuUti, HiIOPerSec, AvgIOPerSec, HiDiskUsage, AvgDsikUsage) VALUES (?, ?, ?, ?, ?,?, ?, ?, ? )');



        if ($handle !== FALSE) 
        {
            // fgets() Gets a line from file pointer and read the first line from $handle and ignore it.   
            fgets($handle);
            // created loop here
            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
            {
            $STM->execute($data);
            }       

            fclose($handle);

        }

    } 
    catch(PDOException $e)
    {
    die($e->getMessage());
    }

echo 'Data imported'; 

}
else 
{
echo 'Could not import Data';
}

?>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接