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

Joh*_*ith 2 php domdocument

我想知道通过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));
}
Run Code Online (Sandbox Code Playgroud)

与:

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

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

Alf*_*ton 8

使用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>
Run Code Online (Sandbox Code Playgroud)