Return to Snippet

Revision: 69549
at July 15, 2015 01:42 by COBOLdinosaur


Initial Code
class fileFormatter
{
    public $map = array();
    public $width = 0;
    public function setMap($inArray) {
        $this->map=$inArray;
    }
    public function setWidth ($inWidth) {
        $this->width=$inWidth;
    }
    public function centerHeading($str) {
        $pad=intval(($this->width-strlen($str))/2);
        $blank=' ';
        return str_pad($blank,$pad).$str.PHP_EOL;
    }
    public function formatLine($data) {
        $dataArray=explode(',',$data);
        $out=NULL;
        for($i=0;$i<count($dataArray);$i++) {
            $out.=str_pad($dataArray[$i],$this->map[$i]);
        }
        return $out.PHP_EOL;
    }

Used in script this way:

$report=new fileformatter();
$heading='Report Heading';
$lineWidth=70;
$columns=array(10,11,15,15,19);
$colHeadings='Source,Id Code,Location,Agent,Status';
$report->setWidth($lineWidth);
$report->setMap($columns);
$infile=fopen('infile.txt', 'r');
$outfile=fopen('outfile.txt', 'a');
fputs($outfile,$report->centerHeading($heading));
fputs($outfile,$report->formatLine($colHeadings));
while (!feof($infile)) {
    $line=trim(fgets($infile));
    fputs($outfile,$report->formatLine($line));
}
$dateLine=' ,Report Run: ' . date("Y-m-d H:i:s");
fputs($outfile,$report->formatLine($dateLine));
fclose( $infile );
fclose( $outfile );

Initial URL
http://coboldinosaur.com/pages/formatting-text-with-string-padding.html

Initial Description
This is a simple PHP class that can be used to produce nicely formatted reports from unorganized data.

Initial Title
Formatted Text Output using str_pad()

Initial Tags
php, text

Initial Language
PHP