With your help I’ve built a Tag class that can write a whole HTML page.
<?php
class Tag
{
protected $sTag;
protected $sAttributes;
protected $sContent;
public function __construct($sTag, $sContent = '')
{
$this->sTag = $sTag;
$this->sContent = $sContent;
}
public function addAttribute($sName, $mValue)
{
$this->sAttributes .= "{$sName}='{$mValue}' ";
}
public function addTag(Tag $oTag)
{
if ($this->sContent == '')
{
$this->sContent = "\
";
}
$this->sContent .= $oTag->render() . "\
";
}
public function render()
{
$temp = trim("{$this->sTag} {$this->sAttributes}");
if ($this->sContent == '')
{
return "<{$temp} />";
}
return "<{$temp}>{$this->sContent}</{$this->sTag}>";
}
}
/************* test *************/
$oTitle = new Tag('title', 'Denny\\'s Object Stuff');
$oKeywords = new Tag('meta');
$oKeywords->addAttribute('name', 'keywords');
$oKeywords->addAttribute('content', 'OOP, PHP5');
$oHead = new Tag('head');
$oHead->addTag($oTitle);
$oHead->addTag($oKeywords);
$oBr = new Tag('br');
$oUsernameField = new Tag('input');
$oUsernameField->addAttribute('type', 'text');
$oUsernameField->addAttribute('name', 'username');
$oPasswordField = new Tag('input');
$oPasswordField->addAttribute('type', 'password');
$oPasswordField->addAttribute('name', 'password');
$oSubmitButton = new Tag('button', 'Click Me!');
$oSubmitButton->addAttribute('type', 'submit');
$oSubmitButton->addAttribute('name', 'submit');
$oSubmitButton->addAttribute('value', 'login');
$oFieldset = new Tag('fieldset');
$oFieldset->addAttribute('style', 'width:200px;');
$oLegend = new Tag('legend', 'Log in please');
$oFieldset->addTag($oLegend);
$oFieldset->addTag($oUsernameField);
$oFieldset->addTag($oBr);
$oFieldset->addTag($oPasswordField);
$oFieldset->addTag($oBr);
$oFieldset->addTag($oSubmitButton);
$oForm = new Tag('form');
$oForm->addAttribute('action', $_SERVER['PHP_SELF']);
$oForm->addAttribute('method', 'post');
$oForm->addTag($oFieldset);
$oBody = new Tag('body');
$oBody->addTag($oForm);
$oHtml = new Tag('html');
$oHtml->addAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
$oHtml->addAttribute('xml:lang', 'en');
$oHtml->addAttribute('lang', 'en');
$oHtml->addTag($oHead);
$oHtml->addTag($oBody);
echo $oHtml->render();
/*
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<title>Denny's Object Stuff</title>
<meta name='keywords' content='OOP, PHP5' />
</head>
<body>
<form action='/~denny/php_manual/xhtml.php' method='post'>
<fieldset style='width:200px;'>
<legend>Log in please</legend>
<input type='text' name='username' />
<br />
<input type='password' name='password' />
<br />
<button type='submit' name='submit' value='login'>Click Me!</button>
</fieldset>
</form>
</body>
</html>
*/
?>
Now I need to create new classes to build selectors and sets of radio buttons and checkboxes.
Thanks guys!