雖然內建的 DOM 函式很棒,但由於它們被設計為支援通用的 XML,因此產生 HTML DOM 會變得特別冗長。我最後寫了這個函式來大幅加快速度。
而不是像這樣呼叫
<?php
$div = $dom->createElement("div");
$div->setAttribute("class","MyClass");
$div->setAttribute("id","MyID");
$someOtherDiv->appendChild($div);
?>
你可以用以下方式完成相同的事情
<?php
$div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
「key1=value;key2=value」的語法使用起來真的很快,但如果你的內容中包含這些字元,顯然就無法使用了。所以,你也可以傳遞一個陣列
<?php
$div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
或是一個陣列的陣列,代表不同的屬性
<?php
$div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");
?>
這是函式
<?php
function newElement($type, $insertInto = NULL, $params=NULL, $content="")
{
$tempEl = $this->dom->createElement($type, $content);
if(gettype($params) == "string" && strlen($params) > 0)
{
$attributesCollection =split(";", $params);
foreach($attributesCollection as $attribute)
{
$keyvalue = split("=", $attribute);
$tempEl->setAttribute($keyvalue[0], $keyvalue[1]);
}
}
if(gettype($params) == "array")
{
if(gettype($params[0]) == "array")
{
foreach($params as $attribute)
{
$tempEl->setAttribute($attribute[0], $attribute[1]);
}
} else {
$tempEl->setAttribute($params[0], $params[1]);
}
}
?>