PHP Library to Avoid Writing HTML


So writing html in php is ugly and error prone. Every opening and closing tag is an opportunity for a typo. It is also quite hard to read the code, upsets indentation (you have the indentation of the html and the indentation of the php code to maintain!), and it can lead to loads of wasted whitepace characters in the html.

I want to use, or make a library that allows me to get around that problem. If I write a table, I want it to be as simple as:

Some helper functions/classes

// prepares an input array for functions and classes
class PrepareInput {
private $inputs = array();

// adds an input value to the array
public function input($name=null, $value=null) {
    if (!is_null($name) && !is_null($value)) {
        $this->inputs[$name] = $value;

// outputs the array and clears it ready for another preparation array to be built
public function output() {
    $out = $this->in;
    $this->inputs = array();
    return $out;


// prepare input shortcut
function p($prepareInputObject, $name, $value) {
    $prepareInputObject->input($name, $value);
function pOut($prepareInputObject) {
    return $prepareInputObject->output();

$p = new PrepareInput;


p($p, 'colTitle', ['Visitor Name', 'Arrival Time', 'Departure Time']);
p($p, 'rows', 
        ['Bob', '9am', ['10pm', 'class', 'lateFinish']],
        ['Jill', '9:40am', '11am'],
        ['Jack', '1pm', '2pm']
$table = new HTMLTable(pOut());
p('rowNum', 0);
p('attribute', ['class', 'morningVisit']);

I haven’t been able to find a library that, is there one I have missed? Or do I have to write one?


Twig if you’re into that sort of thing. It has a couple of features that make it worth using such as extendable templates, though I’m still for the most part a non-believer when it comes to this whole template engine inside a template engine nonsense. It’s better than smarty at least.

Maybe try PHP Heredoc

  $title = 'Table Demo using PHP Heredoc';

  $cols = array('col 1', 'col 2', 'col 3');
  $row1 = array('one',   'two','  three');
  $row2 = array('four',  'five',  'six');
  $row3 = array('seven', 'eight', 'nine');

function fn_row($row, $start='<td>' , $end='</td>')
// BEWARE of the strict syntac for using PHP HereDoc  
  $result = <<<  __ROW
      $start  $row[0]  $end
      $start  $row[1]  $end
      $start  $row[2]  $end

  return $result;

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
<html xmlns="" xml:lang="en-us">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
  body   {background-color:#eee;}
  table  {margin:4.2em; background-color: #fff;}
  td     {padding:0.42em 2em; border:solid 1px #ddd;}
  th     {font-weight: 700;}

  <h1> <?=$title;?> </h1>

      <?= fn_row($cols, '<th>','</th>'); ?>

      <?= fn_row($row1); ?>

      <?= fn_row($row2); ?>

      <?= fn_row($row3); ?>


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.