【问题标题】:How to write fixed width text file with PHP and MYSQL data如何使用 PHP 和 MYSQL 数据编写固定宽度的文本文件
【发布时间】:2012-05-05 08:52:51
【问题描述】:

我在使用 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);

【问题讨论】:

    标签: php text


    【解决方案1】:

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

    其次,试试str_pad()函数。

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

    【讨论】:

    • 嗨 AlienWebguy,我试过你的台词,它只适用于第一行,我无法添加换行符并添加 2 个值,如果有任何问题,请检查下面的代码: $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') 或 die("无法打开文件"); fwrite($fh, str_pad($cust2['Ac_desc'], 100)); fwrite($fh, str_pad($cust2['Add1'], 200)); $stringData = "\n"; fwrite($fh, $stringData); fwrite($fh, str_pad($dtl2['Prod_desc'], 100)); fwrite($fh, str_pad($dtl2['Rate'], 200)); fclose($fh); ob_end_flush(); mysql_close($link);
    • @Shikiryu 反映了他的 PHP 示例,但不是他想要的格式示例。
    • @user1114409 取决于您的机器,您可能需要\r\n 而不仅仅是\n
    • @AlienWebguy 现在工作正常,这是最酷的答案,非常感谢。
    【解决方案2】:

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

    【讨论】:

    • 事件这行得通,但是 AlienWebguy 建议有一种更简单的方法,非常感谢。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2011-08-12
      • 2012-08-16
      相关资源
      最近更新 更多