[ Team LiB ] Previous Section Next Section

26.1 Sprinkling PHP within an HTML Document

The first and most obvious approach to using PHP is to build HTML files as you have always done, inserting PHP tags as if they were HTML tags. This could take the form of repeating HTML that you replace with a call to a PHP function. It could take the form of a large block of PHP code that generates database output. Or it could be a script that processes a form submission. These are all situations in which the impact of PHP on the site is low. This is a good first step for those new to programming. You are able to insert the smallest amount of PHP code as a test. As your experience and confidence grow, so will your reliance on PHP.

Aside from simple tasks, such as inserting today's data with <?php print(date('Y/m/d')); ?>, you can write your own function for wrapping a block of HTML. Listing 26.1 defines a class for printing HTML tables.

Listing 26.1 Formatting function
<?php
    /*
    ** Simple class for creating HTML tables
    */
    class HTMLTable
    {
        static function start($header=FALSE)
        {
            print("<table border=\"1\">\n");

            if(is_array($header))
            {
                print("<tr>\n");

                foreach($header as $h)
                {
                    print("<th>" .
                       strtoupper($h) .
                       "</th>\n");
                }

                print("</tr>\n");
            }
        }

        static function end()
        {
            print("</table>\n\n");
        }

        static function printRow($label, $field)
        {
            print("<tr>\n");

            //label
            if($label !== "")
            {
                print("<th>" .
                    strtoupper($label) .
                    "</th>\n");
            }
            if(!is_array($field))
            {
                $field = array($field);
            }

            foreach($field as $key=>$value)
            {
                print("<td>");
                if($value === "")
                {
                    print("&nbsp;");
                }
                else
                {
                    print($value);
                }
                print("</td>\n");
            }

            print("</tr>\n");
        }

        static function printSet($set)
        {
            foreach($set as $field)
            {
                if(isset($field['label']))
                {
                    $label = $field['label'];
                    unset($field['label']);
                }
                else
                {
                    $label = "";
                }
                HTMLTable::printRow($label, $field);
            }
        }

    }
?>
<html>
<head>
<title>Listing 26-1</title>
</head>

<body>
<p>
This is an example of using a function to repeat
a commonly-used piece of HTML code.  It builds
out a table, like this one.
</p>
<?php
    //show table with labels on the left
    HTMLTable::start();
    HTMLTable::printRow('step 1', 'Start the table');
    HTMLTable::printRow('step 2', 'Print rows');
    HTMLTable::printRow('step 3', 'End the table');
    HTMLTable::end();
?>
<p>
The HTMLTable class allows you to draw all HTML
tables in the same way.  To change the look of
all tables, you need only edit the class.  Cascading
Style Sheets offer similar technology, but implementing
in PHP means we can make unlimited changes to the
data before building the HTML.  It also means we
can neatly indent the data without affecting the
placement on the final document.
</p>
<?php
    //show a table with labels on top
    HTMLTable::start(array('artist', 'song'));
    HTMLTable::printSet(array(
        array('Thelonious Monk', 'Bemsha Swing'),
        array('John Coltrane', 'Spiral'),
        array('Charlie Parker', 'Koko')
        ));
    HTMLTable::end();
?>
</body>
</html>

One benefit of this technique is that every table renders in exactly the same way. Less text to type for each table means less chance of leaving out part of the formula. This is nice to the programmer, who undoubtedly is eager to find a shortcut to typing long segments of identical HTML. A higher degree of quality is ensured. If a call to the function is mistyped, PHP displays an error. If no errors are displayed, the tables are most likely displayed identically and in the correct format.

If the format of the table needs changing, the code must be altered in only one place. Furthermore, PHP offers the opportunity to make changes to the data before displaying it. In Listing 26.1, the code switches labels to uppercase. Note how the class operates in two modes, labels on top or labels on the left.

Another similar use of PHP is to dress up what is essentially CGI output: a large block of PHP surrounded by HTML so that the output of the code simply appears in a larger page. This is a similar approach offered by SSI (Server-Side Includes). An SSI tag may call a CGI and insert the output in its place.

The approach is appropriate in situations in which your site is mostly static, but certain key areas must be dynamic. The advantage is low impact on the Web server. PHP is used only when absolutely needed. In Listing 26.2 the code generates information that doesn't change, but it's easy to imagine code that pulls stock quotes from a database. It eliminates the need to edit the HTML page each time the information changes, but parts that don't change often, like the layout of the page, are left as static HTML.

Listing 26.2 Dressing up CGI output
<html>
<head>
<title>Listing 26-2</title>
</head>
<body>
<h1>Color Chart</h1>
<p>
The following chart displays the colors
safe for displaying in all browsers.  These
colors should not dither on any computer
with a color palette of at least 256
colors.
</p>
<p>
This chart will only display on browsers
that support table cell background colors.
</p>
<?php
    $color = array("00", "33", "66", "99", "CC", "FF");
    $nColors = count($color);

    for($Red = 0; $Red < $nColors; $Red++)
    {
        print("<table>\n");

        for($Green = 0; $Green < $nColors; $Green++)
        {
            print("<tr>\n");


            for($Blue = 0; $Blue < $nColors; $Blue++)
            {
                $CellColor = $color[$Red] .
                    $color[$Green] . $color[$Blue];

                print("<td bgcolor=\"#$CellColor\">");
                print("<tt>$CellColor</tt>");
                print("</td>\n");
            }

            print("</tr>\n");
        }

        print("</table>\n");
    }
?>
</body>
</html>

While Listing 26.2 is an example of dynamic output, you are often faced with the opposite situation. Your site may be completely static, but you need to accept catalog requests. PHP is a good solution for accepting form submissions. The first step is to create an HTML page that asks for name and address. Listing 26.3 demonstrates.

Listing 26.3 Catalog request form
<html>
<head>
<title>Listing 26-3</title>
</head>
<body>
<p>
Please enter name and address to receive a free catalog.
</p>
<form action="26-4.php">
<table>
<tr>
    <td>Name</td>
    <td><input type="text" name="name"></td>
</tr>
<tr>
    <td>Address</td>
    <td><input type="text" name="address"></td>
</tr>
<tr>
    <td>City</td>
    <td><input type="text" name="city"></td>
</tr>
<tr>
    <td>State</td>
    <td><input type="text" name="state"></td>
</tr>
<tr>
    <td>ZIP</td>
    <td><input type="text" name="zip"></td>
</tr>
<tr>
    <td><input type="reset"></td>
    <td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>

The page in Listing 26.3 is a very simple submission form. Each of the input tags will be turned into the _REQUEST array when the submit button is clicked. This calls the script listed in Listing 26.4. The script opens a file named requests.txt for appending and writes each of the form fields into the file. Each field is separated by tab characters, which allows you to import the file into a spreadsheet easily.

Listing 26.4 Form submission
<html>
<head>
<title>Listing 26-4</title>
</head>
<body>
<?
    /*
    ** process form input, append it to file
    */

    $fp = fopen("/tmp/requests.txt", "a");
    if($fp)
    {
        //massage user input
        $_REQUEST['name'] = substr(0, 16, $_REQUEST['name']);
        $_REQUEST['address'] = substr(0, 32, $_REQUEST['address']);
        $_REQUEST['city'] = substr(0, 16, $_REQUEST['city']);
        $_REQUEST['state'] = substr(0, 2, $_REQUEST['state']);
        $_REQUEST['zip'] = substr(0, 10, $_REQUEST['zip']);

        //lock the file
        flock($fp, (LOCK_SH));

        //write request
        fputs($fp, $_REQUEST['name'] . "\t" .
            $_REQUEST['address'] . "\t" .
            $_REQUEST['city'] . "\t" .
            $_REQUEST['state'] . "\t" .
            $_REQUEST['zip'] . "\n");

        //release lock
        flock($fp, LOCK_UN);

        //close the file
        fclose($fp);
    }

?>
<p>
Thank you for your catalog request!
</p>
<p>
<a href="26-3.html">Return to site</a>
</p>
</body>
</html>
    [ Team LiB ] Previous Section Next Section