Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How can I put HTML Code with PHP Code within into a PHP Variable?

I have a question about " and ' in PHP. I have to put a complete <li> element into a PHP variable but this doesn't work, the output is completely false...

    $list = 
"
    <li class=\"<?php if($info[1] < 700) {echo \"half\";} else {echo \"full\";} ?>\">

        <div class=\"onet-display\">

        <?php if ($image = $post->get('image.src')): ?>
            <a class=\"onet-display-block\" href=\"<?= $view->url('@blog/id', ['id' => $post->id]) ?>\"><img class=\"onet-thumb\" src=\"<?= $image ?>\" alt=\"<?= $post->get('image.alt') ?>\"></a>
        <?php endif ?>

        <h1 class=\"onet-thumb-title\"><a href=\"<?= $view->url('@blog/id', ['id' => $post->id]) ?>\"><?= $post->title ?></a></h1>
        <div class=\"uk-margin\"><?= $post->excerpt ?: $post->content ?></div>

        </div>

    </li>
";

Is it because there is PHP Content in the HTML Code? How can I solve this?

Can someone help me and explain why this doesn't work?


1 Answers

<?php ... <?php

Since your string contains PHP tags, I suppose you expect them to be evaluated. The opening PHP tag within another PHP tag is interpreted as a part of the PHP code. For example, the following outputs <?php echo time();:

<?php echo "<?php echo time();";

There are several ways to build a PHP string from PHP expressions.

Concatenation

You can create functions returning strings and concatenate the calls to them with other strings:

function some_function() {
  return time();
}

$html = "<li " . some_function() . ">";

or use sprintf:

$html = sprintf('<li %s>', some_function());

eval

Another way is to use eval, but I wouldn't recommend it as it allows execution of arbitrary PHP code and may cause unexpected behavior.

Output Buffering

If you are running PHP as a template engine, you can use the output control functions, e.g.:

<?php ob_start(); ?>

<li data-time="<?= time() ?>"> ...</li>

<?php
$html = ob_get_contents();
ob_end_clean();
echo $html;

Output

<li data-time="1483433793"> ...</li>

Here Document Syntax

If, however, the string is supposed to be assigned as is, use the here document syntax:

$html = <<<'HTML'
<li data-time="{$variable_will_NOT_be_parsed}">...</li>
HTML;

or

$html = <<<HTML
<li data-time="{$variable_WILL_be_parsed}">...</li>
HTML;
like image 53
Ruslan Osmanov Avatar answered Jul 22 '26 10:07

Ruslan Osmanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!