PHP Formatting A Column (dollar sign) In csv Upload Script - php

I have a script that uploads a csv file with 3 columns (phone, name, amount). The script removes any formatting on the phone, ie; ()- and puts the file on the server. The amount column in the file shows the amount like 125.00 and I need it to show $125.00. Any help would be much appreciated.
$file_destination = '/****/****/****/***/' . $file_name_new;
$contents = file_get_contents($file_tmp);
$contents = str_replace("(","",$contents);
$contents = str_replace(")","",$contents);
$contents = str_replace("-","",$contents);
file_put_contents($file_tmp, $contents);
if(move_uploaded_file($file_tmp, $file_destination)) {

Whether you want to reformat the values strictly for output or store the new formatted data in your CSV file, it's probably going to be more effective to use fgetcsv and fputcsv. Those functions are designed for properly reading in and writing out CSV formatted files.
Example
$rows = [];
if (($handle = fopen($file_tmp, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
list($phone, $name, $amount) = $data;
$phone = str_replace(['(',')','-'], '', $phone);
$amount = sprintf('$%.2f', $amount);
// you can build a new array with the updated values
$rows[] = [$phone, $name, $amount];
// or output directly
echo "$phone | $name | $amount";
}
fclose($handle);
}
// if you want to save the destination with the updated information...
$fp = fopen($file_destination, 'w');
foreach ($rows as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Related

Convert a CSV file to force encapsilation

My ideal fix would be a function that can take a CSV file that does not have forced encapsulation (no quotes around values if the value has no spaces or is just a number) and convert it into a CSV file that makes sure every field is encapsulated with double quotes.
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
convert_file($raw_file, $fixed_file);
//move on with life!!
?>
Thanks for you help!
Use fgetcsv to get the contents of your original csv file and fputcsv (using the fourth parameter) to build the encapsulated file.
For example, supposing your column separator is ; :
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
// Getting contents
$raw_handle = fopen($raw_file, 'r');
$contents = array();
while (($data = fgetcsv($raw_handle, 0, ';')) !== false) {
$contents[] = $data;
}
fclose($raw_handle);
// Putting contents
$fixed_handle = fopen($fixed_file, 'w');
foreach ($contents as $line) {
fputcsv($fixed_handle, $line, ';', '"');
}
fclose($fixed_handle);
//move on with life!!
?>

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

Modify a csv file line by line

I have a big file that I want to modify every line in it.
I want to use PHP to do it quickly :
My file is CSV file ;
20010103,02,00,00,0.9496
20010103,03,00,00,0.9504
20010103,04,00,00,0.9499
I want to make it like this to be able to use it late with Highchart:
[Date.UTC(2001,01,03,02,00,00),0.9496],
[Date.UTC(2001,01,03,03,00,00),0.9504],
[Date.UTC(2001,01,03,04,00,00),0.9499],
How canI loop every line and make this modification ?
See the fgetcsv and fputcsv PHP functions. It will basically be something like:
if (($handle1 = fopen("input.csv", "r")) !== FALSE) {
if (($handle2 = fopen("output.csv", "w")) !== FALSE) {
while (($data = fgetcsv($handle1, 1000, ",")) !== FALSE) {
// Alter your data
$data[0] = '...';
// Write back to CSV format
fputcsv($handle2, $data);
}
fclose($handle2);
}
fclose($handle1);
}
Try this code:
<?php
$filename = 'info.csv';
$contents = file($filename);
foreach($contents as $line) {
$data = explode(",",$line);
$val = "[Date.UTC(".substr($data[0],0,4).",".(substr($data[0],4,2)).",".substr($data[0],6,2).",".$data[1].",".$data[2].",".$data[3]."),".$data[4]."],";
}
?>

fetch file data from ftp & process in php

I have the below script to import data from a csv file on my ftp server, the script works correctly.
$ftp_server = '---Domain---';
$ftp_user_name = '---Uname---';
$ftp_user_pass = '---pass---';
// open some file for reading
$csvfile = '/home/domain/public_html/myfolder/user.csv';
if(!file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
else
{
echo "File exist on this path.\n";
}
user.csv
Email Fname lname
------------------------------
mark#gmail.com mark martin
allan#gmail.com allan lee
I want to fetch data from csv file & pass to php function which will process that data with DB
i.e. add-update user information
I am not getting how to fetch data & pass to function
Any assistance will be appreciated.
Thanks.
$a=array();
$file = fopen('user.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
array_push($a,$line);
}
fclose($file);
//you will get all the content in array $a, you can ride array by using foreach
<?php
$csvfile = '/home/domain/public_html/myfolder/user.csv';
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 0, ",")) !== FALSE) {
// do whatever processing you need with $line array
}
fclose($handle);
}
This solution will give you csv data line by line. If you need all data from csv to an array Use #user1844933's solution

Replace a particular line in a text file using php?

I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.
I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.
This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!
After some edit seems to be working now. I am debugging to see if any errors.
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, '|')
/* manipulate $data array here */
}
fclose($handle);
So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php
$fp = fopen('contacts.tmp', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :
$writing = fopen('contacts.tmp', 'a');

Categories