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

HTML tag encoder

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

Problem

library.php

My own HTML tag encoder that will print HTML codes according to the input.

 $value) {
            $html .= " $name=\"$value\"";
        }

        $html .= ($content === NULL || $content == "") ? " />" : ">$content";

        return $html;
    }
?>


index.php

The test index.php file that will run the HTML encoder from the library.

"title","content"=>"Test Print"))
    );
    echo tag("body",
        tag("div",tag("p","test print".tag("br")."test print"),array())
    );
?>


Output:

test printtest print


Question:

Using this library will make my code more readable when adding more PHP code. Instead of this `, I can use this echo tag("div",$variable);`, but the latter will definitely be longer compared to just typing HTML code.

Should I not create such function and stay with coding HTML?

Solution

You are on the right track, but echo is not the right tool for the job IMO.

Thinking about XML generally we can represent the data like this:

array('tag', $attributes, $children);

The nesting of child elements allows us to do this (children is either an array for a nested element, or a string for a simple text child).

array('div',
      array('class' => 'container'),
      array(array('span', array(), 'One'),
            array('span', array(), 'Two')));


Which represents:


    One
    Two


Using XMLWriter we can write this structure without too much trouble. I do that here in my library. The output from XMLWriter is always indented correctly, regardless of the context a template should appear in.

This is a classic example of matching your data structure to the problem you are solving. By creating a tree to represent the X(HT)ML we can build components of the structure where they belong in our code, rather than being forced to get all of our echo statements in the correct order.

Code Snippets

array('div',
      array('class' => 'container'),
      array(array('span', array(), 'One'),
            array('span', array(), 'Two')));
<div class="container">
    <span>One</span>
    <span>Two</span>
</div>

Context

StackExchange Code Review Q#10809, answer score: 16

Revisions (0)

No revisions yet.