3

In a separate question here on StackOverflow (PHP library for HTML tag generation) I asked if there is a popular or standard HTML tag library for PHP.

A couple of comments showed up questioning the purpose of such a library.

Here's a bit of code from the highly acclaimed book "PHP and MySQL Web Development 4th Edition" by Luke Welling and Laura Thomson:

echo "<td width = \"".$width."%\">
<a href=\"".$url."\">
<img src=\"s-logo.gif\" alt=\"".$name."\" border=\"0\" /></a>
<a href=\"".$url."\"><span class=\"menu\">".$name."</span></a>
</td>";

I thought all the escaping and concatenating looked a little messy, so I cooked up an HTML generation library. The above looks like this using the library:

return td(array('width' => $width . '%'),
    a(array('href' => $url),
        img(array('src' => 's-logo.gif', 'alt' => $name, 'border' => 0))),
    a(array('href' => $url), span(array('class' => 'menu'), $name)));

My question is (and keep in mind, I'm a php newb), what's the idiomatic way to write the above? Is there a cleaner way to write the book example?

Community
  • 1
  • 1
dharmatech
  • 8,979
  • 8
  • 42
  • 88
  • 1
    mediawiki does something similar, have a look how I used it to make a select https://gerrit.wikimedia.org/r/gitweb?p=mediawiki/extensions/AllTimeZones.git;a=blob;f=AllTimeZones.php;h=be501d159b606582947de737c4be994d170bc061;hb=HEAD#l190 – nischayn22 Jun 24 '12 at 06:11

2 Answers2

2

You can use PHP heredoc syntax

<?php

$width=10;
$url="www.google.com";
$name="stackoverflow";

echo <<<EOT
<td width = "$width">
<a href="$url">
<img src="s-logo.gif" alt="$name" border="0" /></a>
<a href="$url"><span class="menu">$name</span></a>
</td>
EOT;
?>


For more information refer Php Manual

Mahesh Meniya
  • 2,627
  • 3
  • 18
  • 17
1

Cleaner - definitely, with heredoc:

echo <<<HTML
<td width="{$width}%">
<a href="{$url}"><img src="s-logo.gif" alt="{$name}" border="0" /></a>
<a href="{$url}"><span class="menu">{$name}</span></a>
</td>
HTML;
poncha
  • 7,726
  • 2
  • 34
  • 38