Page 492 - Beginning PHP 5.3
P. 492

Part III: Using PHP in Practice
                How It Works
                After creating an XHTML page header — including additional CSS rules to style the table — the script
                includes the HTML_Table PEAR package:

                    require_once( “HTML/Table.php” );

                Next, the script sets up an associative array of attributes for the opening <table> tag, then creates a
                new HTML_Table object with these attributes:

                    $attrs = array( “cellspacing” => 0, “border” => 0, “style” => “width: 20em;
                    border: 1px solid #666;” );
                    $table = new HTML_Table( $attrs );

                The two-cell table header row is then created by calling the object’s addRow() method, passing in an
                array of cell data. Notice that the $type argument is set to “th” to ensure that header cells are created:

                    $table->addRow( array( “Sequence #”, “Value” ), null, “th” );

                The rest of the script is much like the script in Chapter 4, with calls to HTML_Table methods replacing the
                old HTML markup. After setting up the number of iterations and the two number variables, the first two
                non-header rows of the table are created:

                    $table->addRow( array( “F<sub>0</sub>”, “0” ) );
                    $table->addRow( array( “F<sub>1</sub>”, “1” ) );

                 Within the loop, new rows are added to the table, again by calling addRow():

                      $table->addRow( array( “F<sub>$i</sub>”, $num2 ) );
                After the loop, the altRowAttributes() method is called to set up the alternate table rows. Counting
                from the row after the header row, every second row is given a CSS class of “alt”:
                    $attrs = array( “class” => “alt” );
                    $table->altRowAttributes( 1, null, $attrs, true );
                Finally, it’s just a case of calling the table object’s toHtml() method to display the table markup:

                    echo $table->toHtml();

                You can see from this example how easy it is to create tables with HTML_Table. The resulting PHP
                code is also clean and easy to modify. Furthermore, once you start using HTML_Table methods such as
                setAutoGrow() and setCellContents() you can create — and modify — quite complex tables in
                just a few lines of code.











              454





                                                                                                      9/21/09   9:14:51 AM
          c15.indd   454
          c15.indd   454                                                                              9/21/09   9:14:51 AM
   487   488   489   490   491   492   493   494   495   496   497