設置 | 登錄 | 註冊

目前共有5篇帖子。

【资料】在两个DOM文档之间复制节点(元素)

1樓 巨大八爪鱼 2015-7-5 10:59
<?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(); // 输出
?>
2樓 巨大八爪鱼 2015-7-5 11:00
输出内容:
<div>text</div>
<div>text</div>


3樓 巨大八爪鱼 2015-7-5 11:09
根据这个原理,我们就可以实现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();
?>
4樓 巨大八爪鱼 2015-7-5 11:10
回复:3楼
Button类的:
function __set($property, $value) {
        parent::__set($property, $value);
    }
要去掉,忘了删了
5樓 巨大八爪鱼 2015-7-5 11:11
call_user_func_array("parent::__construct", func_get_args());
这句话也可以写成:
parent::__construct(...func_get_args());
不过这样写Dreamweaver CC要报错,而PHP本身不报错。

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。