使用DOMDocument在HTML文件中创建元素? [英] Using DOMDocument to create elements in an HTML file?

查看:130
本文介绍了使用DOMDocument在HTML文件中创建元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道通过DOMDocument创建html元素是否是不好的做法。以下是在我的< head> 内构建元标记的功能:

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));
}

相比:

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?

推荐答案

使用DOM方法创建HTML元素可能是个好主意,因为它会(

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.

通过使用 setAttribute 可以稍微简化给出的示例。 :

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>

这篇关于使用DOMDocument在HTML文件中创建元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆