I was wondering whether it would be "bad practice" to create html elements through a DOMDocument. Below is a function in which build the meta tags within my <head>:
$head = new DOMDocument();
foreach($meta as $meta_item) {
$meta_element = $head->createElement('meta');
foreach($meta_item as $k=>$v) {
$attr = $head->createAttribute($k);
$attr->value = $v;
$meta_element->appendChild($attr);
}
echo($head->saveXML($meta_element));
}
versus:
foreach($meta as $meta_item) {
$attr = '';
foreach($meta_item as $k=>$v) {
$attr .= ' ' . $k . '="' . $v . '"';
}
?><meta <?php echo $attr; ?>><?php
}
In terms of cost, when testing this, it seems to be trivial. My question: should I not get in the habit of doing this? Is this a bad idea moving forward?
.innerHTML-type stuff. If you're only adding a few DOM elements, then go ahead and use DOM. If you're building a LOT of elements, then build a string and shove it all into the dom at once.