Ali
Ali

Reputation: 33

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. I'd like to store the result in a variable (which I use as the body of an email).

Upvotes: 0

Views: 115

Answers (4)

Mr. Llama
Mr. Llama

Reputation: 20899

I would use the ob_* functions. Specifically ob_start, ob_get_contents, and 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();

Upvotes: 0

Logan Murphy
Logan Murphy

Reputation: 6230

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;

Upvotes: 0

Krish R
Krish R

Reputation: 22721

Try this, Here added $data variable and $data .= concatenated the results in variable.

    $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;

Upvotes: 0

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

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.

Upvotes: 1

Related Questions