 |
<?php /* 创建两个HTML文档片段 */ $html = new DOMDocument("1.0", "iso-8859-1"); $html2 = new DOMDocument("1.0", "iso-8859-1");
/* 创建节点 */ // 下面两句话是等价的,都可以用 //$x = $html->createElement("div", "text"); $x = new DOMElement("div", "text"); /* 把创建的节点放入文档1 */ $html->appendChild($x); echo $html->saveHTML();
/* 复制到文档2 */ $node = $html2->importNode($x, true); // 创建一个与$x完全一样的,但属于文档2的节点 $html2->appendChild($node); // 放入文档2中 echo $html2->saveHTML(); // 输出 ?>
|
 |
输出内容: <div>text</div> <div>text</div>
|
 |
根据这个原理,我们就可以实现DOMElement类的Extend(扩展),然后把扩展类的实例加入到一个HTML文档树中: <?php class HTMLElement extends DOMElement { private $htmlDoc; protected $readonlyProperties = array(); function __construct() { call_user_func_array("parent::__construct", func_get_args()); $this->htmlDoc = new DOMDocument(); $this->htmlDoc->appendChild($this); } function __get($property) { return $this->getAttribute($property); } function __set($property, $value) { if (!in_array($property, $this->readonlyProperties)) { $this->setAttribute($property, $value); } } public function appendTo(DOMDocument $htmlDoc) { $node = $htmlDoc->importNode($this, true); $htmlDoc->appendChild($node); } public function getHTML() { return $this->htmlDoc->saveHTML(); } }
class Button extends HTMLElement { protected $readonlyProperties = array("type"); function __construct() { parent::__construct("input"); $this->setAttribute("type", "button"); } function __set($property, $value) { parent::__set($property, $value); } }
$html = new DOMDocument("1.0", "iso-8859-1"); $html->formatOutput = true; $btn = new Button(); $btn->value = "dd"; $btn->appendTo($html); echo $html->saveHTML(); ?>
|
 |
回复:3楼 Button类的: function __set($property, $value) { parent::__set($property, $value); } 要去掉,忘了删了
|
 |
call_user_func_array("parent::__construct", func_get_args()); 这句话也可以写成: parent::__construct(...func_get_args()); 不过这样写Dreamweaver CC要报错,而PHP本身不报错。
|