What is this? From this page you can use the Social Web links to save How to Easily Manage HTML Output in PHP to a social bookmarking site, or the E-mail form to send a link via e-mail.

Social Web

E-mail

E-mail It
January 20, 2008

How to Easily Manage HTML Output in PHP

Posted in: PHP

I thought I’d come out with the big guns for our inaugural post. If you’ve ever written a PHP-powered site, you’ll know that the mix of PHP and HTML in the same document can quickly become hideous to read and a nightmare to maintain.

The usual solution is o use a template engine like Smarty, but these are hard to learn and are overkill for smaller projects.

What’s a developer to do?

Enter phpSprockets, a library written at Innova Partners in Columbus OH. Take a normal PHP document that loops over database records and outputs a table:

<table>
	<tr>
		<th>Name</th>
		<th>Address</th>
	</tr>
<?php
// assume $rows has been fetched from the database
$class = 'alt';
 
foreach ($rows as $row) {
	if ($class == '') {
		$class = 'alt';
	} else {
		$class = '';
	}
 
	?>
	<tr class="<?php echo $alt ?>">
	<td><?php echo ucwords($row['name']) ?></td>
	<td><?php echo $row['address'] ?> </td>
	</tr>
	<?php
}
 
echo "</table>";
?>

That’s a lot of code for a simple task, and it’s already a mess. We’re applying a different class to alternating rows, we’re jumping into PHP from HTML, and if we need to do anything complex to this or add more rows this will quickly become unmaintainable. If you had to work with code like this, you’d hate your job eventually.

Let’s see the same code in phpSprockets:

<?php
 
$table = new Sprocket('table');
 
$headers = $table->tr();
$headers->th('Name');
$headers->th('Address');
 
$class = 'alt';
 
foreach ($rows as $row) {
 
	if ($class == '') {
		$class = 'alt';
	} else {
		$class = '';
	}
 
	$tr = $table->tr();
 
	if ($class != '') {
		$tr->class = $class;
	}
 
	$tr->td($row['name']);
	$tr->td($row['address']);
}
 
?>

Okay, the phpSprockets code is longer, but you never leave PHP-mode, and everything’s very readable. I didn’t comment either chunk of code, but once you’ve learned the simple phpSprockets syntax you’ll find that it’s much easier to go back in five months and make changes, which isn’t something you can say about stock PHP without being very rigorous about coding style. Since starting with Innova Partners I’ve switched to using phpSprockets for every PHP project I work on, and the benefits are remarkable.

This is an intentionally brief introduction. For a more in-depth look watch the introductory screencast (by me!), and for full documentation and to download, visit our downloads page.


Return to: How to Easily Manage HTML Output in PHP