note 107777 added to domdocument.createelement
| From: | funkathustra | Date: | Sun, 04 Mar 2012 08:44:23 +0000 |
| Subject: | note 107777 added to domdocument.createelement | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186481@lists.php.net to get a copy of this message | ||
Although the built-in DOM functions are great, since they're designed to support generic XML,
generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically
speed things up.
Instead of calling something like
<?php
$div = $dom->createElement("div");
$div->setAttribute("class","MyClass");
$div->setAttribute("id","MyID");
$someOtherDiv->appendChild($div);
?>
you can accomplish the same thing with:
<?php
$div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold
up if your content has those characters in it. So, you can also pass it an array:
<?php
$div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
Or an array of arrays, representing different attributes:
<?php
$div = newElement("form", $someOtherDiv,
array(array("method","get"), array("action","/refer/?id=5");
?>
Here's the function:
<?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]);
}
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 108.167.38.239
----
Manual Page -- http://www.php.net/manual/en/domdocument.createelement.php
Edit -- https://master.php.net/note/edit/107777
Del: integrated -- https://master.php.net/note/delete/107777/integrated
Del: useless -- https://master.php.net/note/delete/107777/useless
Del: bad code -- https://master.php.net/note/delete/107777/bad+code
Del: spam -- https://master.php.net/note/delete/107777/spam
Del: non-english -- https://master.php.net/note/delete/107777/non-english
Del: in docs -- https://master.php.net/note/delete/107777/in+docs
Del: other reasons-- https://master.php.net/note/delete/107777
Reject -- https://master.php.net/note/reject/107777
Search -- https://master.php.net/manage/user-notes.php