2009-07-13 53 views
0

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

任何帮助将不胜感激。

+1

您可以像创建XML一样构建一个HTML文档,然后使用http://no.php.net/manual/en/domdocument.savehtml.php这个函数对其进行序列化。 – 2009-07-13 21:08:29

回答

2

当它完全归结为它时,可以更简单地使用PHP的现有DOM构造函数之一。

如果这看起来不合理,简单地将一个数组作为类的成员来保持子元素应该会产生奇迹。

+0

你能发布一些链接到一些这些DOM构造函数吗?来自php.net的内容似乎(有限的研究)主要针对XML – 2009-07-13 21:04:37