4

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?

4
  • 3
    it's technically the "correct" way of doing things. but building even a "minor" html document using but DOM operations is hideously painful. most people build the html as a string then stuff the whole string into dom using .innerHTML-type stuff. If you're only adding a few DOM elements, then go ahead and use DOM. If you're building a LOT of elements, then build a string and shove it all into the dom at once. Commented Oct 20, 2013 at 21:05
  • @MarcB thanks Marc! sometimes I just need an expert to tell me what's the right way to do things! Should I delete the question? Commented Oct 20, 2013 at 21:06
  • 2
    There's no reason to delete basic knowledge questions if they're well-formed questions. Level of knowledge is no reason to ever delete a question. Commented Oct 20, 2013 at 21:08
  • 1
    3.5 years later i'm glad you didn't delete this answer. Commented Feb 23, 2017 at 12:59

1 Answer 1

12

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.