HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Add HTML to the page using a PHP Class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thephpusingpageclasshtmladd

Problem

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 ' : '>';

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

        // Closes the tag
        echo '';
    }       
}


Is there someone with a better way of doing it?

Solution

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 Lorem ipsum and the other dolor sit amet.

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 'Lorem ipsum';
echo 'dolor sit amet';


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

Code Snippets

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

Context

StackExchange Code Review Q#37027, answer score: 6

Revisions (0)

No revisions yet.