PHP - 上传CSV文件&打印特定行

时间:2016-11-08 22:52:57

标签: php csv

我正在开发一个Web项目,用户应该能够获取Asana项目导出生成的.csv并导入它,以便打印特定的行。

我实际上可以导入文件:

if ( isset($_POST["submit"]) ) {

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

        //error while uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Error: " . $_FILES["file"]["error"] . "<br />";
        }

        else {
           //error message if file already exists
            if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }

            else {
            //Uploads file in the upload/ folder
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "<strong>Stored in:</strong> " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
         }
      } else {
             echo "No file selected <br />";
     }
}

然后转储数据:

$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num champs à la ligne $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

所以,为了打印一些特定的行,我想到了这一点,它将从11,12,13和11中获取数据。 14行:

$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];

但遗憾的是,我无法弄清楚这一点。

有人有线索/想法/提示吗?任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

实际上,我确实通过循环,设置和回显变量来解决这个问题。我仍然不知道这是否是最佳方式,但它确实有效:

$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];
        for ($c=0; $c < 1; $c++) {
            echo "<table style='min-width:1000px;'><tbody><tr>";
            echo "<td style='width:25%'>" . $kilometrage . "</td>";
            echo "<td style='width:25%'>" . $stationnement . "</td>";
            echo "<td style='width:25%'>" . $perdiem . "</td>";
            echo "<td style='width:25%'>" . $depenses . "</td>";
            echo "</tr></tbody></table>";
        }
    }
    fclose($handle);
}