ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Create your own HTML widgets with PHP

(Page 1 out of 4)

Abstract

In this tutorial you'll learn how to create your own HTML widgets, using nothing more than PHP. You'll be shown how to use an output buffer to create your own HTML tags, and then replacing them with dynamic content. The tutorial will finish by showing you how to create a Repeater Control.

Introduction

HTML comes with many types of tags, and a lot can be done with them, but in some cases you might've wished that it's possible to create your own HTML tags which can do a certain task for you. Unfortunately, you can't just create your own tags, because they won't be recognized by any browser. You could try to get your new tag officially approved by the W3C group, but that'll take years, and doesn't help you right now.

But with a little help from PHP, we can still create our own HTML tags, and have it working in all browsers. In this tutorial I will show you how. First we'll go through the basics of creating a new tag, and after that we'll explore some more advanced functionality. We'll be making use of an output buffer to create our own tags, so if you've never used the output buffer before, it's probably useful to read the following article first: Having fun with PHP's output buffer. Let's get started!

Using an output buffer callback

To create our own HTML tags, we'll have to use an output buffer callback, so let's do that. See the example below:

function parse_mytag($content) {

        return $content;
}

ob_start ('parse_mytag');
?>
Hello World!

Nothing special about the above code snippet, and it's all pretty basic. The reason we have to use an output buffer callback is because we have to parse our own tag just before it gets sent to the browser, since the browser doesn't understand our tag. We have to replace it with regular HTML.

The example below demonstrates a really simple HTML widget:

function parse_mytag($content) {

        // Find the tags
        preg_match_all('/\<mytag\>(.*?)\<\/mytag\>/is', $content, $matches);

        // Loop through each tag
        for ($i=0; $i < count($matches['0']); $i++) {
                $tag = $matches['0'][$i];
                $text = $matches['1'][$i];

                $new = '';
                $new .= $text;
                $new .= ''
;

                // Replace with actual HTML
                $content = str_replace($tag, $new, $content);
        }

        return $content;
}

ob_start ('parse_mytag');
?>
Here is my widget: Hello World

(View Live Demo)

When you run the above code, you will notice that our own tag is never seen by the browser, but instead the actual HTML is seen. In our callback function, we first use a regular expression to retrieve all our custom tags from the page. Then we replace every custom tag with normal HTML, and that's why the browser only sees normal HTML.

By using this callback function, we can create any tag we want and have it do anything we want, because the browser will never see it.

Tags with attributes and no closing tag

We aren't completely there yet, because a HTML tag can also have attributes and it doesn't need to have a closing tag, so we have to slightly modify our regular expression. First, let's catch custom tags with attributes (and later on in this article we'll actually use those attributes!). The example below shows the updated regular expression:

function parse_mytag($content) {

        // Find the tags
        preg_match_all('/\<mytag([^>]*)\>(.*?)\<\/mytag\>/is', $content, $matches);

        // Loop through each tag
        for ($i=0; $i < count($matches['0']); $i++) {
                $tag = $matches['0'][$i];
                $text = $matches['2'][$i];

                $new = '';
                $new .= $text;
                $new .= ''
;

                // Replace with actual HTML
                $content = str_replace($tag, $new, $content);
        }

        return $content;
}

ob_start ('parse_mytag');
?>

Here is my widget: "bar" hello="world">Hello World

As you can see we only made a very minor change, and the rest of the code is still the same.

Our callback function also has to account for tags without a closing tag, when we don't specify any text. A tag without a closing tag looks like this: . To deal with this, the following code is used:

function parse_mytag($content) {

        // Find the tags, WITH closing tag
        preg_match_all('/\<mytag([^>]*)\>(.*?)\<\/mytag\>/is', $content, $matches);

        // Loop through each tag
        for ($i=0; $i < count($matches['0']); $i++) {
                $tag = $matches['0'][$i];
                $text = $matches['2'][$i];

                $new = '';
                $new .= $text;
                $new .= ''
;

                // Replace with actual HTML
                $content = str_replace($tag, $new, $content);
        }

        // Find the tags, without closing tag
        preg_match_all('/\<mytag([^>]*)\/\>/is', $content, $matches);

        // Loop through each tag
        for ($i=0; $i < count($matches['0']); $i++) {
                $tag = $matches['0'][$i];

                $new = '';
                $new .= '';
                $new .= ''
;

                // Replace with actual HTML
                $content = str_replace($tag, $new, $content);
        }

        return $content;
}

ob_start ('parse_mytag');
?>

Here is my widget: "bar" hello="world">Hello World

and here is my second widget:

(View Live Demo)

In the above code snippet we used a second regular expression to catch the tags without a close tag. Obviously, this example doesn't make a lot of sense, and it's pretty pointless to catch these tags, since we'd always have an open tag and closing tag. But in some cases you might only have an open tag, and it's important to catch both cases.

Now that we know how to catch our custom tags, let's looking at putting some functionality in our custom tags.

Next: Using an HTML parser »



One Response to “Create your own HTML widgets with PHP”

  1. RosSoft » Custom HTML Tags (WidgetHelper) Says:

    […] HTML * that contains the subtags and  * It replaces the subtags with the key & value from an associative array. * You must bind the widget to the array through * Example: * ’Elijah Wood’,’Aragorn’=>’Viggo Mortensen’) * $repeaterWidget->bind(’cast’,$array))?> *  *  *     :  *    
     *  *  * Will output the html: *     Frodo:: Elijah Wood *    
     *     Aragorn:: Viggo Mortensen *    
     * * @author RosSoft * @version 0.1 * @license MIT *  * @link http://phpit.net/article/create-html-widgets-php/4/  */require_once(dirname(__FILE__) . DS . ‘widget_helper.php’);class RepeaterWidgetHelper extends WidgetHelper{    //main tags name => array subtags    var $tag=array(                ‘repeater:repeater’=>array(’repeater:key’,’repeater:value’)            );        function tag_repeater_repeater($attr,$inner_html)    {        $array=$this->_get_bound($attr[’array’]);        […]

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & Using output buffer callback
  2. Using an HTML parser
  3. Creating the Repeater Control
  4. Creating two sub tags & Conclusion
Bookmark Article
Download Article
PDF
Download this article as a PDF file