开发者

PHP: Whole HTML page as variable - is there a better way?

I have a large form, in the end of the form a user is presented with a summary:

You have entered:
<table>
    <tr>
        <td>First name</td>
        <td><?php echo $firstname ?></td>
    </tr>
    <tr>
        <td>Last name</td>
        <td><?php echo $lastname ?></td>
    </tr>
</table>

I first designed the summary page and now the thought came to me that it would be nice to send the user this page as a confirmation e-mail. What I have done now is this:

<?php $summarypage = "<table>
        <tr>
            <td>First name</td>
            <td>".$firstname."</td>
        </tr>
        <tr>
            <td>Last name</td>
            <td>".$lastname."</td>
        </tr>
    </table>";
echo $summarypage; ?>

For loops I use $summarypage .= "blabla"; within the loops.

When sending the e-mail I can just take $summarypage and attach it to my e-mail body. Beautiful.

Is what I am doing OK? It seems very "not elegant" to me.

Isn't $summarypage being rendered totally anew when I call it again in my e-mail - meaning all variables concatenated with it (e.g. $fi开发者_运维知识库rstname) will be called again - performance hog?

Is there some kind of "buffer" I could just write the $summarypage variable to, so I have a plain-text variable afterwards? Would $newsummarypage = string($summarypage) do the trick?


Ignore performance on that level, it won't matter. If the method you show works for you, use it.

An alternative that makes things a bit more readable (because you won't need PHP openers / closers) is HEREDOC:

<?php $summarypage = <<<EOT
<table>
 <tr>
  <td>First name</td>
  <td>$firstname</td>
  </tr>
  <tr>
   <td>Last name</td>
   <td>$lastname</td>
  </tr>
</table>
EOT;
?>


I think you are a bit confused about how strings/variables work in php. A little example might help

$s = "hello"; //stores the sequence 'h' 'e' 'l' 'l' 'o' in $s
$s = $s." world";//take the sequence stored in $s add the sequence ' world', 
                 //and store in $s again
echo $s; // prints 'hello world'. That is what $s contains, what $s is

$summary = "<div>".$firstname."</div>"; // take '<div>', lookup what $firstname
                 //contains and add that, then add '</div>' and then store this 
                 //new string thing('<div>Ishtar</div>') in $summary.

echo $summary; //$summary here knows nothing about $firstname, 
               //does not depend on it

All variables are evaluated when you use them. (Well, most of the time you use variables by evaluating them.)


$summarypage is a string, so it's just a bit of data assigned to a variable - a plain-text variable, as you said. Once the data is assigned to $summarypage, the work is done. You can happily write it out into pages, emails, databases and text files with no additional performance hits related to $summarypage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜