PHP Html Tag Builder

About this time last year I was learning how to use CakePHP for a job and it took awhile to get used to, but when I finally started getting the hang of it I started to see how powerful some simple PHP functions could be. I don’t use it anymore, but since then I’ve built a collection of classes based on the things that I really liked CakePHP would do. Now when I write PHP apps I use these constantly for outputting html, creating forms, handling post/get data, etc. I was just thinking up a way to combine pretty much all html tags into one function and wanted to share it.

Now, I’m not going to say this will do anything you want, because it probably won’t and I’m not going to test it with every thing I can think of. However, this should handle all of your basic tags properly and therefore come in very helpful for those who like to stick on the PHP side of things instead of swapping between PHP/HTML constantly when building pages.

Here’s the basis, we’re going to use one function to output html tags for us. So it has to know what the tag is, what to put in the tag (like id, class, etc), whether it should close the tag and what content to put in the tag (if any). Before I get started writing this I want to note that I’m writing this for the site only, I use an htmlHelper class I’ve created that handles all kinds of different stuff. So please report errors! And don’t assume if something doesn’t work it’s your error and not mine :D.

Alright, let’s look at the function definition:

function build_html_tag($tagName, $tagData = array(), $close = true, $content = null)
{
     //code to build tag here
}

Now, let’s break those down so we know what they all are.
$tagName: This will be the first thing that goes inside our opening tag. So if we are building a div tag, our tagName would be ‘div’. If we are building a link, our tagName would be ‘a’.
$tagData: This can be an array of anything else that should go in the opening tag. If you are new to PHP and don’t know much yet about key=>value arrays, you need to go read up on those because they are very powerful! So, in here, let’s say we wanted to give have id=‘blue’ and class=‘nuggets’. For $tagData we would pass:
array('id'=>'blue', 'class'=>'nuggets')
$close: A simple true or false depending on if you want to leave the tag open to put some data in or to have it closed.
$content: I leave this last because a lot of the time you may not want to close the tag in which case you probably don’t want to put any content in it because you are going to handle the content yourself following the function call. But if you do want to close it, you can pass it some content here to put inside the tag.

Note with the parameters above the $tagName is the only required part because that’s all tags require.

Alright, everyone should still be with me so far and now it’s time to build the actual function. The first parts easy:

//a variable to use to store our tag in
$htmlTag = '<';
//put the tag name in there
$htmlTag .= $tagName;

That simply just created a variable which we will return at the end with our full tag and started it off with the opening ‘<’ and our tag name. Next, it’s time to add in any $tagData that was passed in.

//check for tagData
if (!empty($tagData))
{
    //loop through all the tagData
    foreach($tagData as $key => $val)
    {
        //it's important to remember the space at the beginning and the quotes around
        //the $val because HTML likes quotes around it's values
        $htmlTag .= ' '.$key.'="'.$val.'"';
    }
    //that's everything that will go into our opening tag, so we can close it now
    $htmlTag .= '>';
}

Okay, now that will loop through anything in the tagData array and add it to the htmlTag we are building. It will take literally anything, so keep that in mind as it can hurt/help you depending on how you use it!

Next, we are actually going to check for the content even though it’s not our next parameter. I noted above why I ordered the parameters as I did, but we have to check for content before trying to close the tag.

//simply tack on the content if there is any, nothing trick here!
if ($content != null)
{
     $htmlTag .= $content;
}

I don’t think that needs any explaining, the final step is to simply close the tag if requested.

//check for closing the tag
if ($close)
{
    $htmlTag .= '</'.$tagName.'>';
}

At the end of the function you have two choices really. I personally prefer to just return the final piece of data, but you could also echo it out right there. Additionally, you could provide this as a 5th parameter if you chose.

//return the data
return $htmlTag;
//if you want, you could choose to echo out here instead
//echo $htmlTag;

Now, it’s all about using this function really. Because once it’s built (as long as it works) you never have to touch it again! So, let’s look at some examples of how to use it:

//a simple div tag
echo html_tag_builder('div', array('id'=>'blue', 'class'=>'nuggets'), true, 'This is my html_tag_builder built div tag);
//result: <div id="blue" class="nuggets">This is my html_tag_builder built div tag</div>

//an html link
echo html_tag_builder('a', array('href'=>'#', 'onclick'=>'toggleForm();'), true, 'Toggle Form');
//result: <a href="#" onclick="toggleForm();">Toggle Form</a>
//an input tag
echo html_tag_builder('form', array('name'=>'loginForm', 'method'=>'post', 'action'=>'login.php', 'onsubmit'=>'return checkLoginForm();'), false);
//result: <form name="loginForm" method="post" action="login.php" onsubmit="checkLoginForm();">
//an h1
echo html_tag_builder('h1', array(), true, 'Title');
//result: <h1>Title</h1>

Alright, I think that’s enough of those. If you decide to use the function I’m sure you’ll figure out how to use it in plenty of different situations. I think it’s important to note to why I like things like this, because it doesn’t seem to really shorten what you are doing. But it does allow you to stay within PHP to do everything. I hate putting opening and closing PHP tags everywhere because it just gets messy really fast and functions like this are really dynamic and powerful in PHP. I also think with some extra effort you can add on to the function and make it even more powerful.

One suggestion would be to check for the $tagData array having arrays inside of it and handling those. Then you’d be able to output an entire select statement with options from the html_tag_builder call. If you check for arrays in the options you can allow optgroups inside that select.

At this point you may want to branch out the part that loops through the tagData array so that you can call it recursively. Maybe I’ll post on that in the future because it would be a pretty useful function to have if you are using key val arrays a lot.

That does it for the demo function though! I’ll post the whole thing below, if you have errors/problems or you like it please let me know! Give a shout to awesomeghost to if you end up using it somewhere. Enjoy.

function build_html_tag($tagName, $tagData = array(), $close = true, $content = null)
{
	//a variable to use to store our tag in
	$htmlTag = '<';
	//put the tag name in there
	$htmlTag .= $tagName;
	//check for tagData
	if (!empty($tagData))
	{
	    //loop through all the tagData
	    foreach($tagData as $key => $val)
	    {
	        //it's important to remember the space at the beginning and the quotes around
	        //the $val because HTML likes quotes around it's values
	        $htmlTag .= ' '.$key.'="'.$val.'"';
	    }
	    //that's everything that will go into our opening tag, so we can close it now
	    $htmlTag .= '>';
	}
	//simply tack on the content if there is any, nothing trick here!
	if ($content != null)
	{
	     $htmlTag .= $content;
	}
	//check for closing the tag
	if ($close)
	{
	    $htmlTag .= '</'.$tagName.'>';
	}
	//return the data
	return $htmlTag;
	//if you want, you could choose to echo out here instead
	//echo $htmlTag;
}

• Luke Stebner •




---

Comment

 
---