如何使用PHP和MYSQL数据编写固定宽度的文本文件


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

我在使用 php 和 mysql db 中的数据编写固定宽度的文本文件时遇到问题。请在下面找到我有一个客户表的格式:客户名称为 100 个字符宽度客户地址宽度为 200 个字符。

我需要以以下格式打印这些内容。

3M India Limited                         Plot 48-51 Electronic City
Biocon Ltd                               20th KM Hosur Road,Electronic city

现在我的客户名称不断变化,但我需要修复此宽度,然后打印地址。下面是我的代码,我手动提供空格,这会导致数据在写入文本文件时变得随意。

PHP代码:

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

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

其次,尝试 str_pad(( 函数。

fwrite($fh, str_pad($cust2['Ac_desc'], 100));
fwrite($fh, str_pad($cust2['Add1'], 200));
首先,

您确定第一列的静态宽度,例如 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);

您可以将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 ''