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