我正在研究PHP中的HTML类,以便我们可以保持所有的HTML输出一致。不过,我在围绕逻辑方面遇到了一些麻烦。我正在使用PHP,但任何语言的答案都可以使用。如何正确创建HTML类?
我希望类正确嵌套的标签,所以我希望能够像这样调用:
$html = new HTML;
$html->tag("html");
$html->tag("head");
$html->close();
$html->tag("body");
$html->close();
$html->close();
类代码正在与阵列在幕后,并在推数据,弹出数据关闭。我相当肯定我需要创建一个子阵列,使其位于<html>
的下方,但我无法弄清楚逻辑。下面是实际的代码到HTML
类,因为它主张:
class HTML {
/**
* internal tag counter
* @var int
*/
private $t_counter = 0;
/**
* create the tag
* @author Glen Solsberry
*/
public function tag($tag = "") {
$this->t_counter = count($this->tags); // this points to the actual array slice
$this->tags[$this->t_counter] = $tag; // add the tag to the list
$this->attrs[$this->t_counter] = array(); // make sure to set up the attributes
return $this;
}
/**
* set attributes on a tag
* @author Glen Solsberry
*/
public function attr($key, $value) {
$this->attrs[$this->t_counter][$key] = $value;
return $this;
}
public function text($text = "") {
$this->text[$this->t_counter] = $text;
return $this;
}
public function close() {
$this->t_counter--; // update the counter so that we know that this tag is complete
return $this;
}
function __toString() {
$tag = $this->t_counter + 1;
$output = "<" . $this->tags[$tag];
foreach ($this->attrs[$tag] as $key => $value) {
$output .= " {$key}=\"" . htmlspecialchars($value) . "\"";
}
$output .= ">";
$output .= $this->text[$tag];
$output .= "</" . $this->tags[$tag] . ">";
unset($this->tags[$tag]);
unset($this->attrs[$tag]);
unset($this->text[$tag]);
$this->t_counter = $tag;
return $output;
}
}
任何帮助将不胜感激。
您可以像创建XML一样构建一个HTML文档,然后使用http://no.php.net/manual/en/domdocument.savehtml.php这个函数对其进行序列化。 – 2009-07-13 21:08:29