如何分割csv文件,以便可以从中制作2张表?

时间:2019-01-22 12:50:50

标签: php csv

我需要从此csv文件制作2个表。我如何在第二行之后分割文件,

csv文件的外观如下。

  

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

Palle_nr; Varenummer; Ordre_nr; Operatoer; Maskin_nr

1234; 1234_2019_01_14_17_11_23; 1234; TN; 1234

;;;;

名称;基准;属性;条件;类型

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

这就是我的代码的样子。再次,我要这段代码要做的是在第二行之后拆分csv文件。所以我用Palle_nr得到一张桌子 和带有名称的表

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);
    }
  }
}  

如果您需要整个代码,则可以重新创建问题。然后将其上传,但以为是很多代码。

其他读取文件的方式也受到赞赏。我只需要能够分割文件即可。

1 个答案:

答案 0 :(得分:1)

我需要在您的代码中提出很多问题,但是由于文件中的前四行是可预测的,因此无需循环就可以使用它们。

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));
        }
    }
}

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

相关问题