user1114409 user1114409 - 1 month ago 10
PHP Question

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

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

Answer

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