首页 > 解决方案 > 如何拆分 csv 文件以便我可以从中制作 2 个表?

问题描述

我需要从这个 csv 文件中创建 2 个表。如何在第二行之后拆分文件,

这就是 csv 文件的外观。

我已将我需要的内容标记为标题。我不需要这些行的数据。

Palle_nr;Varenummer;Ordre_nr;Operatoer;Maskin_nr

1234;1234_2019_01_14_17_11_23;1234; 田纳西州;1234

;;;;

名称;基准;属性;标准;类型

1) 高度 130;;avg(L)Y;;inspection_dimension_scalar

这就是我的代码的样子。我希望这段代码再次在第二行之后拆分 csv 文件。所以我得到一个带有 Palle_nr 的表和一个带有 Name 的表

if (isset($_POST['btn-upload'])){

copy("$sourcepath/$latest_filename","$copy/$latest_filename");

$row = 1;
if (($openfile = fopen("$copy/$latest_filename", "r")) !== FALSE) {

    $csvuser->createPalleTable($latest_filename);
    while ($getpdata = fgetcsv($openfile, 1000, ";")) {
        $getpdata = array_map("utf8_encode", $getpdata);
        $totalp = count($getpdata);

        $row++;

        for ($i=0; $i < $totalp; $i++) {
            $pdata = implode(";", $getpdata);
            $palledata = explode(";", $pdata);
        }
        $csvuser->insertPalleTable($latest_filename,$palledata);
        }

///////// This is where i want the file to split ///////

     $header = fgetcsv($openfile, 1000, ";");
     $header = array_map("utf8_encode", $header);
     $totalheader = count($header);
     for ($i=0; $i < $totalheader; $i++) {
         $headerdata = implode(";", $header);
         $th = explode(";", $headerdata);
         }

   $csvuser->createCsvTable($latest_filename);
   while ($getdata = fgetcsv($openfile, 1000, ";")) {
   $getdata = array_map("utf8_encode", $getdata);
   $total = count($getdata);

   $row++;

   for ($c=0; $c < $total; $c++) {
        $csvdata = implode(";", $getdata);
        $fncsvdata = explode(";", $csvdata);
    }
     $csvuser->insertCsvTable($latest_filename,$fncsvdata);
    }
  }
}  

如果您需要整个代码,那么您可以重新创建问题。然后生病上传它,但认为它会是很多代码。

其他读取文件的方式也值得赞赏。我只需要能够拆分文件。

标签: phpcsv

解决方案


我必须在您的代码中提出很多问题,但是由于文件中的前四行是可预测的,因此您可以在不循环的情况下使用它们。

if (isset($_POST['btn-upload'])){
    copy("$sourcepath/$latest_filename","$copy/$latest_filename");

    if (($openfile = fopen("$copy/$latest_filename", "r")) !== false) {

        $header1 = fgetcsv($openfile, 1000, ";"); // consume, but don't use

        $csvuser->createPalleTable($latest_filename);
        $csvuser->insertPalleTable($latest_filename, array_map("utf8_encode", fgetcsv($openfile, 1000, ";")));

        $delimiting_row = fgetcsv($openfile, 1000, ";"); // consume, but don't use 

        $header2 = fgetcsv($openfile, 1000, ";"); // consume, but don't use

        $csvuser->createCsvTable($latest_filename);
        while ($getdata = fgetcsv($openfile, 1000, ";")) {
            $csvuser->insertCsvTable($latest_filename, array_map("utf8_encode", $getdata));
        }
    }
}

这是完全未经测试的(并从我的手机发布)。


推荐阅读