0

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

3 回答 3

4

首先,确保您的Ac_descAdd1是定义的常量或引用它们以将其视为关联索引。

其次,尝试str_pad()函数。

fwrite($fh, str_pad($cust2['Ac_desc'], 100));
fwrite($fh, str_pad($cust2['Add1'], 200));
于 2012-05-05T08:59:02.247 回答
1

首先,您确定第一列的静态宽度,例如 100 个字符。

然后尝试使用此代码

$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);
于 2012-05-05T09:03:23.473 回答
0

您可以将 MySQL 的RPAD()函数与它的SELECT ... INTO OUTFILE命令一起使用:

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 ''
于 2012-05-05T09:12:26.073 回答