PHP格式化文本文件

时间:2014-05-20 14:42:03

标签: php text formatting

如何格式化内容如下所示的文本文件:

Col 1     Col 2     Col 3    ...
abcd      ab        a
ab        a         abcd

每个字符串都有不同的长度。

我用PHP代码达到的输出看起来很难看:

Col 1     Col 2     Col 3    ...
abc   abc   abc
abc      abc        abc

我创建文本文件的PHP代码如下:

$tab = "\t\t";
$txtString = "";
foreach ($teams->get() as $team) {
    $class = $classes->getClasses($team["class_id"]);
    $club = $clubs->get($team["club_number"]);
    $txtString .= $class[0]["class_name"] . $tab;
    $txtString .= $team["club_number"] . " " . $club[0]["name"] . $team["team_number"] . $tab;
    $txtString .= $team["team_leader_name"] . $tab;
    $txtString .= $team["team_leader_street"] . $tab;
    $txtString .= $team["team_leader_place"] . $tab;
    $txtString .= $team["team_leader_phone"] . "\n";
}

$file = "Mannschaftsfuehrer.txt";
file_put_contents($file, $txtString);

任何人都可以帮我获得格式正确的文本文件吗? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

你需要用空格填充,为此使用sprintf:

sprintf("10%s", "string" ); // "string" has a length of 6, and so, first 4 characters will be " "( space );

sprintf文档: http://www.php.net/manual/ro/function.sprintf.php

  

(PHP 4,PHP 5)sprintf - 返回格式化字符串

答案 1 :(得分:0)

如果与sprintf相比,执行时间非常短。&空间可以改变。所以我更喜欢使用自己的功能。

这是一个函数,它返回足够空格的字符串。 这里str是你要格式化的字符串。

 function getFormatted($str,$col_width){
  $n=$col_width-strlen($str);
  for(;$n>0;$n--)
  $str.=' ';
  return $str;
}