目前共有5篇帖子。 內容轉換:不轉換▼
 
點擊 回復
261 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)
 

本帖信息

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