How to write fixed width text file with PHP and MYSQL data - php

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

Related

Starting a newline for CSV in foreach loop?

I need to start a new line every time it loops through and adds to the CSV document that is getting generated.
Code:
if(is_array($results_top_pages->getRows())){
$name = rand();
$myfile = fopen("bin/".$name.".csv", "w") or die("Unable to open file!");
foreach($results_top_pages->getRows() as $top_page){
$txt = array($top_page[0]. ",".$top_page[1]);
fputcsv($myfile, $txt);
}
fclose($myfile);
}
I have tried the following:
- array($top_page[0]. ",".$top_page[1]. "\n");
- array($top_page[0]. ",".$top_page[1]. "\r\n");
- array($top_page[0]. ",".$top_page[1]. "<br>");
As well as all the above with '' instead of ""
Still no luck. Everything that is generated is all one line when opened in excel.
Thanks in advance.
It should detect the line endings. From putcsv doc:
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Hope this helps.
Lose the quoted comma in $txt = array($top_page[0]. ",".$top_page[1]); Do this instead:
$txt = array($top_page[0], $top_page[1]);
fputcsv automatically puts line endings. What you're actually doing in your example is sending a single element array.

Using tabs spacing in php for text file

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

php create txt file need cr lf

I have a problem with a txt file.
I create with:
$myFile = $data_stampa . ".txt";
$fo = fopen($myFile, 'w') or die("can't open file");
$stringData .= $var1 . $var2 . $var3 . "\r\n";
fwrite($fo, $stringData);
fclose($fo);
My file are ok, but when I put on a reader, say I need "\r\n".
Where are my mistake??
EDIT
For example, I create a line like this
1717/04/2014 2Surname Name 124/12/1969 100000216100000216PASORcgllk71xk 100000216
the white space are a fix number, for example for surname I need 50 character. for name 30.
At the end of each line I need to put my \r\n but tho reader don't see.

PHP creating text file with dynamic data from MYSQL issue

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

we are getting .txt file but not getting proper alignment

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

Categories