Reputation: 1780
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?
Upvotes: 4
Views: 6506
Reputation: 5463
Using DOM methods to create HTML elements can be a good idea, as it will (in most cases) handle escaping of special characters for you.
The example given could be simplified slightly by using setAttribute
:
<?php
$doc = new DOMDocument;
$html = $doc->appendChild($doc->createElement('html'));
$head = $html->appendChild($doc->createElement('head'));
$meta = array(
array('charset' => 'utf-8'),
array('name' => 'dc.creator', 'content' => 'Foo Bar'),
);
foreach ($meta as $attributes) {
$node = $head->appendChild($doc->createElement('meta'));
foreach ($attributes as $key => $value) {
$node->setAttribute($key, $value);
}
}
$doc->formatOutput = true;
print $doc->saveHTML();
// <html><head>
// <meta charset="utf-8">
// <meta name="dc.creator" content="Foo Bar">
// </head></html>
Upvotes: 12