PHP没有读取整个CSV文件

时间:2011-06-16 06:54:32

标签: php

我编写了一段简单的代码来测试两个参数并将用户转发到链接。

error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$secure_box=$_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$data=fgetcsv($fh);
$first_name=$data[0];
$date=$data[1];
$url=$data[2];
{
if($secure_box == $first_name AND $date>=$now)
{
   header("Location: $url");
   exit();
}
else
  {
   header("Location: http://localhost/x/delivery_method.html");
  }
    exit;
?>

我的问题是没有读取整个CSV文件。我该怎么办?

3 个答案:

答案 0 :(得分:8)

由于您只调用fgetcsv一次,因此未读取整个文件。 fgetcsv一次只读取一行,您需要将该代码放在循环中。

这是一个如何在循环中使用fgetcsv的示例,来自http://www.php.net/fgetcsv的php文档:

<?php
// Example #1 Read and print the entire contents of a CSV file
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

答案 1 :(得分:2)

这是我能够提出来的。希望它是正确的

<?php
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$name_value = $_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$line = 1;
if (($handle = fopen("db.csv", "r")) !== FALSE)
{
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
        $num = count($data);
        $line++;
        for ($c = 0; $c < $num; $c++)
        {
            if ($name_value == $data[0] AND $data[1] >= $now)
            {
               header("Location: $data[2]");
               exit();
            }
            else
            {
                header("Location: http://localhost/x/client_unauthorized.html");
            }
        }
    }
    fclose($handle);
}   
?>

答案 2 :(得分:1)

您可以循环读取整个文件,直到EOF,并依次检查每一行。

相关问题