1

How can I format a text file that the content looks like this:

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

Each string have a different length.

The output I have reached with my PHP code looks quite ugly:

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

My PHP code to create the text file follows:

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

Can anyone help me to get a well formatted text file? Thanks in advance.

2
  • Please reduce your code to a short, self-contained example. Commented May 20, 2014 at 14:43
  • You'd need to detect what the longest string is for every column for every record, then use that as your spacing guide. Which basically means two passes through the text. one to detect sizes, one to actually do the formatting. Commented May 20, 2014 at 14:45

2 Answers 2

1

If you compare with sprintf execution time is quite low.& spaces can be changed. SO i prefer using my own function.

Here is a function which returns you string with enough spaces. Here str is string you want to format.

 function getFormatted($str,$col_width){
  $n=$col_width-strlen($str);
  for(;$n>0;$n--)
  $str.=' ';
  return $str;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Use this function - is bad idea. The beautiful solution of this problem: use sprintf function with offset formatting.
1

You need to pad with spaces, and for that use sprintf:

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

sprintf documentation: http://www.php.net/manual/ro/function.sprintf.php

(PHP 4, PHP 5) sprintf — Return a formatted string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.