目前共有5篇帖子。 字體大小:較小 - 100% (默認)▼  內容轉換:大陆简体▼
 
點擊 回復
578 4
【资料】在两个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本身不报错。
 

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:578 回複數:4
評論數: ?
作者:巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2015-7-5 11:11
 
©2010-2025 Purasbar Ver2.0
除非另有聲明,本站採用共享創意姓名標示-相同方式分享 3.0 Unported許可協議進行許可。