LearningROR LearningROR - 4 months ago 10
PHP Question

Unable to insert data in CSV file PHP

I am in process of inserting data in the desired CSV file from another CSV file.

CSV file is creating fine with out any problem but its is not insert array data in file.

It only inserts header on the first row.

Below is code I am trying:

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";

}
}


Here is my CSV file data:

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

Answer

There are so many ways of going about this... including str_getcsv($csvData). However here we'd go for something old-school & a bit twisted;-). We would create a Function that uses Regex and a Looping Construct to build-up the relevant CSV Data Structure. The Function below illustrates how. Also note that although we mentioned that this is a somewhat twisted, old-school approach: don't be fooled... because it does its thing still ;-).

    <?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)
Comments