Re: Embedding HTML Within a PHP Statement [message #176009 is a reply to message #176004] |
Tue, 15 November 2011 22:15 |
Ross McKay
Messages: 14 Registered: January 2011
Karma:
|
Junior Member |
|
|
On Mon, 14 Nov 2011 20:54:25 +0100, houghi wrote:
> I would use something like:
> <?php
> echo "<table><tbody>";
> foreach ($someDBResult as $oneRow);
> echo "<tr><td>".$oneRow["firstName"]."</td>
> <td>".$oneRow["initials"]."</td>
> </tr>";
> endforeach;
> echo "</tbody></table>";
> ?>
> [...]
Or you could even use HEREDOC (IMHO, it's purpose-made for the job):
<?php
echo "<table><tbody>";
foreach ($someDBResult as $oneRow) {
echo <<<HTML
<tr>
<td>{$oneRow["firstName"]}</td>
<td>{$oneRow["initials"]}</td>
</tr>
HTML;
}
echo "</tbody></table>";
?>
Of course, you might need to htmlspecialchars() those values, which you
can't do in a HEREDOC... unless you happen to have an object reference
with a method that calls htmlspecialchars():
<?php
class X {
function html($text) { return htmlspecialchars($text); }
}
$x = new X();
echo "<table><tbody>";
foreach ($someDBResult as $oneRow) {
echo <<<HTML
<tr>
<td>{$x->html($oneRow["firstName"])}</td>
<td>{$x->html($oneRow["initials"])}</td>
</tr>
HTML;
}
echo "</tbody></table>";
?>
Given that I mainly put my code inside classes, it's pretty easy to
provide that html() method for HEREDOCs to call as $this->html(...)
However, what the OP found is pretty common in templates where the focus
is on HTML, not PHP; the PHP is there to add functionality but the
template is really about the design, and often the people editing
templates are proficient in HTML and CSS but not PHP.
--
Ross McKay, Toronto, NSW Australia
"The lawn could stand another mowing; funny, I don't even care"
- Elvis Costello
|
|
|