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"] . "
";
}
$file = "Mannschaftsfuehrer.txt";
file_put_contents($file, $txtString);
Can anyone help me to get a well formatted text file? Thanks in advance.
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;
}
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