Reg H
Reg H

Reputation: 285

How to write fixed width text file with PHP

I'm trying to do something that should be easy, but having problems.

All I want to do is generate a report from a MySQL table, and have it as a plain .txt file. I need the file fixed width, so everything lines up and looks good. I'm going to use the courier font, and it's just going to be a barebones table, but how do I actually get everything to line up, the way a fixed-width file should?

Do I have to build up an array of values padded with spaces to get them the same width? or is there a php function to begin writing at a specific position?

Thanks again for the help!

Upvotes: 6

Views: 7112

Answers (2)

Lucas Panik
Lucas Panik

Reputation: 31

I would still add a substr before, in case the input value of str_pad is greater than the PAD, the original value is returned, breaking its fixed width.

Example:

var_dump(str_pad('Some string with more than 20 input characters', 20));
string (46) "Some string with more than 20 input characters"

With substr:

var_dump(substr(str_pad('Some string with more than 20 input characters', 20), 0, 20));
string (20) "Some string with mor"

Working from right to left:

var_dump(str_pad('Some string with more than 20 input characters', 20, "", STR_PAD_LEFT));
string (46) "Some string with more than 20 input characters"
var_dump(substr(str_pad('Some string with more than 20 input characters', 20, "", STR_PAD_LEFT), -10));
string (10) "characters"

Upvotes: 2

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

Take a look at the str_pad method. E.g.

str_pad('Somevalue', 20, " ", STR_PAD_LEFT); 

Will left-pad the string "Somevalue" with spaces, giving

"           Somevalue"

Whereas

str_pad('Somevalue', 20);

Will right-pad the string with spaces, giving:

 "Somevalue           "

Upvotes: 10

Related Questions