2016-07-17 66 views
1

我正在從另一個CSV文件插入所需CSV文件中的數據。無法將數據插入CSV文件PHP

CSV文件創建沒有任何問題,但它沒有插入數組文件中的數據。

它只在第一行插入標題。

下面是代碼,我想:

date_default_timezone_set('America/New_York'); 
set_time_limit(0); 
ini_set("memory_limit", -1); 

$realPath = realpath(dirname(__FILE__)); 
$path  = $realPath.'/3pltracking/'; 
$files = scandir($path); 
$FilePath = $path.$files[2]; 
$result = array(); 
$date  = date('m-d-Y_his'); 

if (file_exists($FilePath)) 
{ 
    if (($handle = fopen($FilePath, "r")) !== FALSE) 
     { 
      $i=0; 
      while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) 
      { 
       $i++; 
       if($i==1) continue; 

       //$list = array('$data[2],$data[25],$data[4],$data[30],$data[41],$data[27]'); 
       echo $data[2].",".$data[25].",".$data[4].",".$data[30].",".$data[41].",".$data[27]; 
       echo "<br>"; 
       $list = array($data[2].",".$data[25].",".$data[4].",".$data[30].",".$data[41].",".$data[27]); 

      // the problem is here I believe as it is empty array if I check it outside while loop 
      } 

     fclose($handle); 

     $headers = array('ReferenceNumber', 'TotalCartons', 'ShipCarrier', 'TrackingNum', 'FreightPP', 'TotalWeight'); 

     $fp = fopen($realPath.'\3pltracking\TrackingFiles\Tracking_File_'.$date.'.csv', 'w'); 

     fputcsv($fp, $headers); 

     foreach ($list as $line) { 

      $val = explode(",", $line); 

      fputcsv($fp, $val); 

     } 

     fclose($fp); 

    } else { 

     $body = "File Not Found"; 

     } 
    } 

這裏是我的CSV文件中的數據:

TransactionNumber,CustomerName,ReferenceNumber,PurchaseOrderNumber,ShipCarrier,ShipService,ShipBilling,ShipAccount,EarliestShipDate,CancelDate,Notes,ShipToName,ShipToCompany,ShipToAddress1,ShipToAddress2,ShipToCity,ShipToState,ShipToZip,ShipToCountry,ShipToPhone,ShipToFax,ShipToEmail,ShipToCustomerName,ShipToDeptNumber,ShipToVendorID,TotalCartons,TotalPallets,TotalWeight,TotalVolume,BOLNum,TrackingNum,TrailerNum,SealNum,ShipDate,ItemNumber,ItemQuantityOrdered,ItemQuantityShipped,ItemLength,ItemWidth,ItemHeight,ItemWeight,FreightPP,WarehouseID,LotNumber,SerialNumber,ExpirationDate,Supplier,Cost,FulfillInvShippingAndHandling,FulfillInvTax,FulfillInvDiscountCode,FulfillInvDiscountAmount,FulfillInvGiftMessage,SoldToName,SoldToCompany,SoldToAddress1,SoldToAddress2,SoldToCity,SoldToState,SoldToZip,SoldToCountry,SoldToPhone,SoldToFax,SoldToEmail,SoldToCustomerID,SoldToDeptNumber,FulfillInvSalePrice,FulfillInvDiscountPct,FulfillInvDiscountAmt 
242328,PARADIGM TRENDS,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0 
33,d,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0 
44,PARAdgdfDIGM TRENDS,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0 
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,BY3M,176,176,11,1,1,11,,,,,,,,,,,,,,,,,,,,,,,,,,0,0,0 
+0

CSV表示** C ** omma - ** S ** eparated ** V ** alues。您是否將** COMMA(,)**隱藏在您的CSV文件或....中? – Poiz

+0

沒有它沒有隱藏。基本上我手動創建CSV文件使用這些數據,然後解析它,然後選擇所需的字段,並嘗試創建csv文件 – LearningROR

+0

啊......好吧......請你給我們一個**的內容片段.. ./3pltracking/whatever.csv**文件?只是前4條線將是非常有用的... – Poiz

回答

1

還有的要對這個......包括str_getcsv($csvData)這麼多的方法。然而,在這裏,我們會去找點東西old-school &有點扭曲;-)。我們將創建一個函數,該函數使用RegexLooping構造來構建相關的CSV數據結構。下面的函數說明了如何。另外請注意,儘管我們提到這是一種有點扭曲的老派方法:不要被愚弄... ,因爲它還在做它的事情;-)

<?php 

     $csvSourceFile   = __DIR__ . "/1.csv"; 
     $csvPreferredColumns = array('ReferenceNumber', 'TotalCartons', 'ShipCarrier', 'TrackingNum', 'FreightPP', 'TotalWeight'); 
     $newCsvStrut   = processCSVData($csvSourceFile, $csvPreferredColumns, __DIR__ . "/test.csv"); 

     /** 
     * @param $csvSource     // PATH TO THE MAIN CSV FILE 
     * @param array $csvPreferredColumns // ARRAY OF HEADER COLUMN-NAMES TO BE EXTRACTED FROM MAIN CSV 
     * @param null $newCSVFileName  // NAME OF THE NEW CSV FILE TO BE CREATED. 
     * @return string 
     */ 
     function processCSVData($csvSource, array $csvPreferredColumns, $newCSVFileName=null){ 
      // GET THE CONTENTS OF THE CSV FILE & STORE IT IN A VARIABLE 
      $csvData  = file_get_contents($csvSource); 

      // SPLIT THE CONTENTS OF THE CSV FILE LINE BY LINE: THAT IS; AT THE END OF EACH LINE 
      // THUS CONVERTING THE DATA TO AN ARRAY... 
      $arrCsvLines = preg_split("#\n#", $csvData); 

      //FILTER OUT UNWANTED EMPTY VALUES FROM THE ARRAY 
      $arrCsvLines = array_filter($arrCsvLines); 

      // CREATE SOME VARIABLES TO BE USED WITHIN THE LOOP... 
      $strDataFinal = ""; 
      $arrDataMain = $arrDataFinal = array(); 

      // IF THERE IS MORE THAN ONE LINE IN THE ARRAY WE CREATED ABOVE, 
      // THEN CONTINUE PROCESSING THE DATA... 
      if($arrCsvLines && count($arrCsvLines)>0){ 
       // SINCE THE HEADER IS ALWAYS THE FIRST LINE IN THE CHAIN, 
       // WE EXPLICITLY EXTRACT IT AND STORE IT IN A VARIABLE FOR LATER USE 
       $arrCsvHeaders = preg_split("#\,([\s\t]+)?#", $arrCsvLines[0]); 

       // NOW WE LOOP THROUGH ALL THE LINES WE CREATED BY SPLITTING THE CONTENTS 
       // OF THE CSV FILE AT THE END-OF-LINE BOUNDARY 
       foreach($arrCsvLines as $key=>$arrCsvLine){ 
        // WE DON'T WANT ANYTHING AT INDEX "0" SINCE IT IS THE HEADER 
        // AND WE ALREADY DEALT WITH IT ABOVE.... 
        // SO IF THE INDEX $key IS NOT 0, WE CAN CONTINUE PROCESSING 
        if($key != 0){ 
         $arrDataTemp = array(); 
         $arrTempCsvData = preg_split("#\,([\s\t]+)?#", $arrCsvLine); 
         foreach($arrTempCsvData as $iKey=>$sData){ 
          $arrDataTemp[$arrCsvHeaders[$iKey]] = $sData; 
         } 
         $arrDataMain[] = $arrDataTemp; 
        } 
       } 

       foreach($arrDataMain as $iKey=>$subData){ 
        $arrTempFinal = array(); 
        foreach($subData as $key=>$data){ 
         if(in_array($key, $csvPreferredColumns)){ 
          $arrTempFinal[$key] = $data; 
         } 
        } 
        $arrDataFinal[] = implode(",\t", $arrTempFinal); 
       } 

       $arrDataFinal = array_merge(array(implode(",\t", $csvPreferredColumns)), $arrDataFinal); 
       $strDataFinal = implode("\n", $arrDataFinal); 

       if($newCSVFileName){ 
        file_put_contents($newCSVFileName, $strDataFinal); 
       } 
      } 
      return $strDataFinal; 
     } 

     var_dump($newCsvStrut); 
     // PRODUCES SOMETHING SIMILAR TO THE LINES BELOW: 
     string 'ReferenceNumber, TotalCartons, ShipCarrier, TrackingNum, FreightPP, TotalWeight 
       123810, CUSTOMER PICK UP, 30, 30, , 0 
       123810, CUSTOMER PICK UP, 30, 30, , 0 
       123810, CUSTOMER PICK UP, 30, 30, , 0 
       , , , , , ' (length=204) 
+0

您的解決方案非常完美。 :D嚴肅地說,它的偉大方法,即使是舊學校的事情;-) – LearningROR