PHP embedded in html

Hi
I execute this code

<?php

$array = array(1 => 'one', 2 => 'two', 3 => 'three');

$html = <<<TEMPLATE
<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?php echo $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>
TEMPLATE;
echo $html;
?>

But I get this output

<table>
    <?php foreach(Array as =>): ?>
    <tr>
        <td><?php echo ; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

I was expecting the php foreach loop to be properly created.

What am I doing wrong?

Do you have PHP running on your server? You are running this through a server, I take it?

The code within the heredoc is treated as part of the string, so is not parsed as php.

1 Like

Thanks for pointer,
So I need to use echo?

If you are wanting the output there and then, you may use echo. If you need a variable to hold the sting until output at a later time, you could append the string to the variable within the loop.

<?php

$array = array(1 => 'one', 2 => 'two', 3 => 'three');

$html = <<<EOT
<table>

EOT;

foreach($array as $key=>$value) {
    $html .= <<< EOT
    <tr>
        <td>{$key}</td>
    </tr>

EOT;
}

$html .= <<<EOT

</table>

EOT;

echo $html;
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.