0

我正在使用 PHP 编写一个 HTML 类,以便我们可以保持所有 HTML 输出一致。但是,我在理解逻辑时遇到了一些麻烦。我正在使用 PHP,但任何语言的答案都可以。

我希望类正确嵌套标签,所以我希望能够像这样调用:

$html = new HTML;

$html->tag("html");
$html->tag("head");
$html->close();
$html->tag("body");
$html->close();
$html->close();

类代码在幕后处理数组,推送数据,弹出数据。我相当肯定我需要创建一个子数组来拥有<head>under <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;
    }
}

任何帮助将不胜感激。

4

1 回答 1

2

归根结底,使用 PHP 的现有 DOM 构造函数之一可能会更简单。

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

于 2009-07-13T20:46:04.067 回答