我正在研究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