I was trying to make my life easier making a class or something that would create HTML tags in a faster way. I ended up with something that I wouldn't consider the best practice. Take a look:

 * Add HTML to the page
 * Add HTML to the page based on arrays with the tag names. It's gonna open and close the tags.
 * @param array tags The name of the tags
 * @param array attributes The attributes of the tags if you want
 * @param array The elements you want inside the tags
function addHtml($tags = null, $attributes = null, $innerHtml = null)
    for($i = 0; $i < count($tags); $i++) {
        // Opens the tag
        echo '<' . $tags[$i];

        // If there're attribures, show them and close
        // If not, just closes the tag
        echo !empty($attributes) ? ' ' . $attributes[$i] . '>' : '>';

        // Show something you wanna put inside the tag. Another tag, text, anything
        echo $innerHtml[$i];

        // Closes the tag
        echo '</' . $tags[$i] . '>';

Is there someone with a better way of doing it?


1 Answer 1


When it comes to outputting HTML from PHP, there are a couple of alternatives:

  • Using a MVC framework which will separate the logic (Controller) from the data (Model) and the output (View).
  • Include files that contains HTML, and that can use some PHP as well ("Templates"). MVC frameworks normally makes use of this.
  • For short HTML, I believe there is nothing that beats using PHP's echo function and write the HTML you want manually.

A big problem with your current function is that to output several HTML tags, you'd have to write things that actually belongs together very far apart. For example:

addHTML(array("p", "p"), 
  array('class="some"', 'class="other"'), 
  array("Lorem ipsum", "dolor sit amet"));

It's not very readable to see that one tag will become <p class="some">Lorem ipsum</p> and the other <p class="other">dolor sit amet</p>.

If you really really want to have some self-written PHP function for this, then I suggest putting things that belong together, together. Something like this:

addHTML(array(array("p", "class" => "some", "Lorem ipsum"), 
             array("p", "class" => "other", "dolor sit amet")));

However, simply writing this would be so much simpler, and a whole lot easier to read: (Especially for people who are used to reading HTML)

echo '<p class="some">Lorem ipsum</p>';
echo '<p class="other">dolor sit amet</p>';

(My PHP is a bit rusty but I hope you get the idea)


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.