[英]Store PHP and HTML output within variable
I have the following code: 我有以下代码:
echo "Hi " . $firstName . ", <br /><br /> text <br /> <br />";
$i = 0;
foreach ($urls as $key) {
print_r ('<a href="' . ($key) . '">');
print_r($names[$i] . "</a>");
echo "<br /> <br />";
$i++;
}
echo "text, <br /><br /> text";
This prints out a message with a list of links generated by the foreach loop. 这会打印出一条消息,其中包含由foreach循环生成的链接列表。 I'd like to store the result in a variable (which I use as the body of an email).
我想将结果存储在变量中(用作电子邮件的正文)。
You can do as 你可以做
$body = '';
foreach ($urls as $key) {
$body .= '<a href="' . ($key) . '">';
$body .= $names[$i] . "</a>";
$body .= "<br /> <br />";
$i++;
}
Here initializing a var $body and inside the loop concatenating the result into body so that you can use it later. 在这里初始化var $ body并在循环内部将结果连接到body中,以便以后使用。
Try this, Here added $data
variable and $data .=
concatenated the results in variable. 试试看,这里添加了
$data
变量和$data .=
将结果串联在变量中。
$data = "Hi " . $firstName . ", <br /><br /> text <br /> <br />";
$i = 0;
foreach ($urls as $key) {
$data .='<a href="' . ($key) . '">'.$names[$i] . "</a><br /> <br />";
$i++;
}
$data .="text, <br /><br /> text";
echo $data;
Just concat the new strings with a summation of the previous strings. 只需将新字符串与先前字符串的总和连接即可。
$output = "Hi $firstName,<br/><br/>text<br/><br/>";
$i = 0;
foreach ($urls as $key) {
$output .= '<a href="' . $key . '">' . $names[$i] . "</a><br/><br/>";
$i++;
}
$output .= "text,<br/><br/>text";
echo $output;
I would use the ob_*
functions. 我会使用
ob_*
函数。 Specifically ob_start
, ob_get_contents
, and ob_end_clean
特别是
ob_start
, ob_get_contents
和ob_end_clean
In your case, it would be: 在您的情况下,它将是:
ob_start();
echo "Hi " . $firstName . ", <br /><br /> text <br /> <br />";
$i = 0;
foreach ($urls as $key) {
print_r ('<a href="' . ($key) . '">');
print_r($names[$i] . "</a>");
echo "<br /> <br />";
$i++;
}
echo "text, <br /><br /> text";
$body = ob_get_contents();
ob_end_clean();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.