Formatted Text Output using str_pad()


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. class fileFormatter
  2. {
  3. public $map = array();
  4. public $width = 0;
  5. public function setMap($inArray) {
  6. $this->map=$inArray;
  7. }
  8. public function setWidth ($inWidth) {
  9. $this->width=$inWidth;
  10. }
  11. public function centerHeading($str) {
  12. $pad=intval(($this->width-strlen($str))/2);
  13. $blank=' ';
  14. return str_pad($blank,$pad).$str.PHP_EOL;
  15. }
  16. public function formatLine($data) {
  17. $dataArray=explode(',',$data);
  18. $out=NULL;
  19. for($i=0;$i<count($dataArray);$i++) {
  20. $out.=str_pad($dataArray[$i],$this->map[$i]);
  21. }
  22. return $out.PHP_EOL;
  23. }
  24.  
  25. Used in script this way:
  26.  
  27. $report=new fileformatter();
  28. $heading='Report Heading';
  29. $lineWidth=70;
  30. $columns=array(10,11,15,15,19);
  31. $colHeadings='Source,Id Code,Location,Agent,Status';
  32. $report->setWidth($lineWidth);
  33. $report->setMap($columns);
  34. $infile=fopen('infile.txt', 'r');
  35. $outfile=fopen('outfile.txt', 'a');
  36. fputs($outfile,$report->centerHeading($heading));
  37. fputs($outfile,$report->formatLine($colHeadings));
  38. while (!feof($infile)) {
  39. $line=trim(fgets($infile));
  40. fputs($outfile,$report->formatLine($line));
  41. }
  42. $dateLine=' ,Report Run: ' . date("Y-m-d H:i:s");
  43. fputs($outfile,$report->formatLine($dateLine));
  44. fclose( $infile );
  45. fclose( $outfile );

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.