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

时间:2013-10-20 21:03:28

标签: 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));
}

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

就成本而言,在测试时,它似乎微不足道。我的问题:我不应该养成这样做的习惯吗?这是一个不错的想法向前发展吗?

1 个答案:

答案 0 :(得分: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>
相关问题