无法在CSV文件PHP

时间:2016-07-17 10:33:02

标签: php csv fputcsv

我正在从另一个CSV文件中插入所需CSV文件中的数据。

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

1 个答案:

答案 0 :(得分:1)

有很多方法可以解决这个问题......包括str_getcsv($csvData)。不过,我们在这里寻找old-school&amp;有点扭曲;-)。我们将创建一个使用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)