Skip to content Skip to sidebar Skip to footer

PHP Echo Inside Echo

I'm trying to call an HTML/PHP content that it's inside my database using: When the row is called the HTML appears correctly but the

Solution 1:

That is some of the ugliest code I have ever seen...

<?php 
echo '
<h3>Hello</h3>';

while ($row_indiosct = mysql_fetch_assoc($indiosct))
{
  echo '
    <div class="indios">
      <a href="indio.php?id='.$row_indiosct['id'].'">
        <img src="galeria/indios/'. $row_indiosct['foto'].'" alt="'.$row_indiosct['nome'].'" />
      <br />'.$row_indiosct['nome'].'</a>
    </div>';
} 
?>

You could also use the HEREDOC syntax.


Solution 2:

Don't do this. Multi-line echoes, especially when you've got embedded quotes, quickly become a pain. Use a HEREDOC instead.

<?php 

echo <<<EOL
<h3>Hello</h3>
...
<div class"indios">
...
EOL;

and yes, the PHP inside your echo will NOT execute. PHP is not a "recursively executable" language. If you're outputting a string, any php code embedded in that string is not executed - it'll be treated as part of the output, e.g.

echo "<?php echo 'foo' ?>"

is NOT going to output just foo. You'll actually get as output

<?php echo 'foo' ?>

Solution 3:

You have misunderstood how PHP works. PHP is processed by the server. When it encounters your script, it sees the following:

<?php echo "some long piece of text that you have told PHP not to look at" ?>

What is the reasoning behind trying to nest PHP calls inside strings?


Solution 4:

evaluate code php in string using the function eval(): this post Execute PHP code in a string

<?php
$motto = 'Hello';
$str = '<h1>Welcome</h1><?php echo $motto?><br/>';
eval("?> $str <?php ");

http://codepad.org/ao2PPHN7

also if your need the code buffer output in a string also you can using the ob_start() method:

<?php ob_start(); ?>
<h3>Hello</h3>;

<?php 
  while ($row_indiosct = mysql_fetch_assoc($indiosct)){ ?>

<div class="indios">
  <a href="indio.php?id='<?php echo $row_indiosct['id']'">
    <img src="galeria/indios/'<?php echo $row_indiosct['foto'].'" alt="'.$row_indiosct['nome'].'" />
  <br />'.$row_indiosct['nome'].'</a>
</div>';

<?php } ?>

Post a Comment for "PHP Echo Inside Echo"