I'm reading a CSV file and printing the data from the CSV file to 2 .txt files. The output of the text files are as follows
John
Georgina,Sinclair,408999703657,cheque,"First National Bank",Fourways,275.00,12/01/2012
Toby,Henderson,401255489873,cheque,"First National Bank",Edenvale,181.03,12/13/2012
Here is my code:
$file_handle = fopen("debitorders.csv", "r") or die("can't open debitorders.csv");
$absaFile = fopen("ABSA.txt", "w") or die("can't open ABSA.txt");
$firstNationalBankFile = fopen("First National Bank.txt", "w") or die("can't open First National Bank.txt");
while (!feof($file_handle) ) {
$debitorders = fgetcsv($file_handle, 1024, ",");
if ($debitorders[4] == "ABSA"){
print_r ($debitorders[4] . "<br />");
fputcsv($absaFile, $debitorders);
$ABSA_bank = "ABSA";
fopen("ABSA.txt", "a");
file_put_contents('ABSA.txt', $ABSA_bank, FILE_APPEND);
}
if ($debitorders[4] == "First National Bank"){
$FNB_bank = "First National Bank";
print_r ($debitorders[4] . "<br />");
fputcsv($firstNationalBankFile, $debitorders);
$FNB_bank = "First National Bank";
fopen("First National Bank.txt", "a");
file_put_contents('First National Bank.txt', $FNB_bank, FILE_APPEND);
}
}
fclose($file_handle);
fclose($absaFile);
fclose($firstNationalBankFile);
How can I put tab spaces in the output file instead of commas, so that the output instead looks like this:
John
GeorginaSinclair 408999703657 cheque First National Bank Fourways 275.0012/01/2012
TobyHenderson 401255489873 cheque First National Bank Edenvale 181.0312/13/2012
Any help would be appreciated. Thank You
I did something similar a while back although it was the other way around. I replaced tabs with commas. Here is the code I used:
preg_replace('/[ ]{2,}|[\t]/', ',', $string);
The code above removed two tabs and replaced with one comma. So maybe try it this way:
preg_replace(',', '/[ ]{1,}|[\t]/', $string);
As per php manual
int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
So you can try
fputcsv($absaFile, $debitorders ,"\t");
Related
I have a Excel data converted from XLSX to CSV, then I need to upload it to my site. The data shown like this on CSV but changed after upload.
// On Excel (CSV)
Row Description
1 Enjoy this life without drugs
2 Life is so short, so enjoy it
After uploading to site and inserted to MySQL it's look like this.
// On MySQL
Row Description
1 Enjoy?this life without?drugs
2 Life is?so?short, so?enjoy it
// On PHP ( (echo loop).
Row Description
1 Enjoy�this life without�drugs
2 Life is�so�simple, so�enjoy it
I was checked on my CSV, it just space that changed into ? and �. So, I'm trying to replace that but all failed using :
// $the_string = Line of text Description.
1. str_replace("�", " ", $the_string);
2. str_replace("�", " ", $the_string);
3. str_replace("�", " ", $the_string);
4. str_replace("?", " ", $the_string");
But, If I'm test it only on <?php str_replace("�", " ", "a�b"); ?>, It's working.
I don't know where is the mistake.
This is my source code :
public function upload()
{
$config = array(
"upload_path" => "./uploads/",
"allowed_types" => "csv"
);
$this->load->library("upload", $config);
$this->load->helper("file");
$this->upload->initialize($config);
$upload = $this->upload->data();
$file = base_url()."uploads/{$upload['file_name']}";
$file_handle = fopen($file, "r");
$check_line = 0;
while ( ! feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
$check_line++;
}
fclose($file_handle);
if ($check_line > 1)
{
$file_handle2 = fopen($file, "r");
while ( ! feof($file_handle2))
{
$line_of_text = fgetcsv($file_handle, 1024);
$description = $line_of_text[1];
$this->model->insert_description($description);
}
fclose($file_handle);
}
}
Try with preg_replace():
preg_replace('/\x{FFFD}/u', ' ', $the_string);
Try it here.
Attention: This will remove the � character from the string, but ONLY if it is the real character stored in the string.
The � character may appear in substitution of every character that isn't encoded properly accordingly with the encoding used by, in this case, PHP.
To remove all non-printable characters use this:
preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $the_string);
Try it here.
I am having an array in PHP which contains some line breaks (\n) also as the array elements. I am writing these array elements into the CSV file using fwrite statement as below.
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line);
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);
ltrim is not working as it trims only leading white spaces. I have to replace the extra space in the beginning of the CSV file while it is getting written.
The CSV file is getting written as below.
Jack 1234
John 3456
Jason 3321
I am expecting to write into the CSV file as below.
Jack 1234
John 3456
Jason 3321
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line," ");
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);
You can use PHP's substr() function and a while loop, like this:
$name=" Jack 1234";
while(substr($name,0,1)==" ") $name=substr($name,1);
echo $name;//Jack 1234
Just change
$line1 = ltrim($line);
to this
$line1 = ltrim($line," ");
I am writing a Text file with php using mysql db fields, which are dynamic in nature. I am unable to keep the column width intact, pl see the below data and columns to get a better idea of what I mean.
Text file output:
450 65445 90900 87954 112
90900 45875 24565 15484 KA01 23232
php script for the above:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
if ($quer2[DCNO1]>0){fwrite($fh, str_pad($quer2[DCNO1],19, " ", STR_PAD_LEFT));} if ($quer2[DCNO2]>0) {fwrite($fh, str_pad($quer2[DCNO2],6, " ", STR_PAD_LEFT));} if ($quer2[DCNO3]>0) {fwrite($fh, str_pad($quer2[DCNO3],6, " ", STR_PAD_LEFT));} if ($quer2[DCNO4]>0) {fwrite($fh, str_pad($quer2[DCNO4],6, " ", STR_PAD_LEFT));}
fwrite($fh, str_pad($dchd2['PO_No'],13, " ", STR_PAD_LEFT));
$stringData = "\n";
fwrite($fh, $stringData);
if ($quer2[DCNO5]>0) {fwrite($fh, str_pad($quer2[DCNO5],19, " ", STR_PAD_LEFT));} if ($quer2[DCNO6]>0) {fwrite($fh, str_pad($quer2[DCNO6],6, " ", STR_PAD_LEFT));} if ($quer2[DCNO7]>0) {fwrite($fh, str_pad($quer2[DCNO7],6, " ", STR_PAD_LEFT));} if ($quer2[DCNO8]>0) {fwrite($fh, str_pad($quer2[DCNO8],6, " ", STR_PAD_LEFT));}
fwrite($fh, str_pad($dchd2['Vehicle_no'],20, " ", STR_PAD_LEFT));
$stringData = "\n";
fwrite($fh, $stringData);
fclose($fh);
Now if one value in the column is 0 then the space gets removed because of my IF condition, in such a situation, how do i calculate the space and give those extra spaces.
text file output if one of the values are 0 in my IF condition:
450 90900 112
90900 45875 24565 15484 KA01 23232
Use tab stops ("\t"). It ensures each item on different lines start on the same columns.
It means that when item is 2 chars long and can't fill the 4 space tab, 2 whitespaces are added.
Bear in mind: different editors have different notions for tabs, some typically insert spaces instead of tabs.
Edit: Actually more simple solution will be to have an else clause and write str_pad("", 20);
Your code is VERY busy, try centralizing it all through a function where you can handle the '0' in one place. Something like the below (this code has not been tested, but should give you the right idea.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
function writepad($str,$pad)
{
global $fh;
if($str==0) $str=" "; //handle the case where str is 0, replace it with a space
fwrite($fh,str_pad($str,$pad,STR_PAD_LEFT));
}
writepad($quer2[DCNO1],19);
writepad($quer2[DCNO2],6);
writepad($quer2[DCNO3],6);
writepad($quer2[DCNO4],6);
writepad($quer2['PO_No'],13);
fwrite($fh, "\n");
writepad($quer2[DCNO5],19);
writepad($quer2[DCNO6],6);
writepad($quer2[DCNO7],6);
writepad($quer2[DCNO8],6);
writepad($quer2['Vehicle_no'],20);
fwrite($fh, "\n");
fclose($fh);
I have an issue in writing fixed width text file using php and data from mysql db. Pl find below format where I have a customer table:
customer name of 100 char width
customer address of 200 chars width.
I need to print these in the below format.
3M India Limited Plot 48-51 Electronic City
Biocon Ltd 20th KM Hosur Road,Electronic city
Now my customer name keeps varying, but I need to fix this width and then print Address. Below is my code where I am manually giving the spaces which is causing the data to go haphazard when written in a text file.
php Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = " ".$cust2[Ac_desc];
fwrite($fh, $stringData);
$stringData = " ".$cust2[Add1]."\n";
fwrite($fh, $stringData);
fclose($fh);
First, make sure your Ac_desc and Add1 are defined constants or quote them to treat as associative indexes.
Second, try the str_pad() function.
fwrite($fh, str_pad($cust2['Ac_desc'], 100));
fwrite($fh, str_pad($cust2['Add1'], 200));
First you decide a static width for your first column, say 100 characters.
Then try with this code
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = " ".$cust2[Ac_desc];
$spaces = 100 - strlen($cust2[Ac_desc]); // get the number of spaces to add
fwrite($fh, $stringData);
$stringData = str_repeat(" ",$spaces).$cust2[Add1]."\n";
fwrite($fh, $stringData);
fclose($fh);
You can use MySQL's RPAD() function together with its SELECT ... INTO OUTFILE command:
SELECT
RPAD(ColumnA, #width, ' '),
RPAD(ColumnB, #width, ' '),
-- etc.
INTO OUTFILE '/path/to/file.prn'
FIELDS TERMINATED BY '' ENCLOSED BY '' ESCAPED BY ''
LINES TERMINATED BY '\n' STARTING BY ''
we are getting the following texfile_screenshot1.JPG when we are exporting data to .txt file
we need output which is shown in texfile_screenshot2.JPG
following is the code
$myFile = "user_password.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$newline ="\r\n";
fwrite ($fh,$newline);
$stringData1 = $_POST['uname1']." "." "." " ;
fwrite($fh, $stringData1);
$stringData1 =$_POST['password1']." "." "." ";
fwrite($fh,$stringData1);
$stringData1 = $_POST['email1']." "." "." ";
fwrite($fh, $stringData1);
fclose($fh);
You need to use tabs (\t) instead of spaces to get column-like alignement
Here is your example updated
$myFile = "user_password.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$newline ="\r\n";
fwrite ($fh,$newline);
$stringData1 = $_POST['uname1']."\t" ;
fwrite($fh, $stringData1);
$stringData1 =$_POST['password1']."\t";
fwrite($fh,$stringData1);
$stringData1 = $_POST['email1']."\t";
fwrite($fh, $stringData1);
fclose($fh);
You need to print a "\t" (tab) instead of three concatenated spaces.
Like so
$stringData1 = $_POST['uname1']."\t";
fwrite($fh, $stringData1);
EDIT: This may not always work though, if your the difference in length of the strings are more than one tab. If you're creating a tab delimited file, this will work. If you want some sort of column-view this is not a good approach.. (another edit; paxdiablos answer is better for the second method.)
All you seem to be doing is appending three spaces to the end of each field. Perhaps you should be doing something more like:
$stringData1 = substr($_POST['uname1'] . " ",0,14) . " ";
fwrite($fh, $stringData1);
In other words, make sure the field is 14 characters or more, the truncate it to 14.
Or better yet, use the printf facilities:
fprintf ($fh, "%-14s ", $_POST['uname1']);
In fact, your entire segment could be compressed to something like:
$myFile = "user_password.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fprintf ($fh, "\r\n%14s %14s %14s", $_POST['uname1'], $_POST['password1'],
$_POST['email1']);
fclose($fh);
Well, you're writing uname1, password1 and email1 to a file, separated with three spaces (and for what reason ever, three more spaces at the end of each line).
Use str_repeat to add as many spaces as you need: http://php.net/manual/de/function.str-repeat.php
Like this:
$stringData1 = $POST['uname1'] . str_repeat(" ", $longest_uname - strlen($POST['uname1']) + 1);
fwrite($fh, $stringData1);
$stringData1 = $POST['password1'] . str_repeat(" ", $longest_password - strlen($POST['password1']) + 1);
fwrite($fh, $stringData1);
$stringData1 = $POST['email1'] . str_repeat(" ", $longest_email - strlen($POST['email1']) + 1);
fwrite($fh, $stringData1);
You'll need to find out $longest_uname, $longest_password, $longest_email first by iterating through your array and finding the longest string for each of your columns.
If you don't need the last column to be right-padded with spaces, you can skip the "longest_email"-part.
EDIT: Of course the "tab"-solutions mentioned here will work, too, but only if the difference between the lengths of your strings in one column will not exceed one tab. Also the "substr(..., 14)"-method will work, but only if no string is longer than 14 characters ...