使用 DOMDocument 在 HTML 文件中创建元素


Using DOMDocument to create elements in an HTML file?

我想知道通过 DOMDocument 创建 html 元素是否是"不好的做法"。下面是一个在我的<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));
}

对:

foreach($meta as $meta_item) {
    $attr = '';
    foreach($meta_item as $k=>$v) {
        $attr .= ' ' . $k . '="' . $v . '"';
    }
    ?><meta <?php echo $attr; ?>><?php
}

就成本而言,在测试时,这似乎是微不足道的。我的问题:我不应该养成这样做的习惯吗?这是一个坏主意吗?

使用 DOM 方法创建 HTML 元素可能是一个好主意,因为它(在大多数情况下)会为您处理特殊字符的转义。

给出的示例可以通过使用以下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>