3

I have been stuck trying to write PHP code inside some HTML tags I set up.

I have a variable inside a .php file called $content, and I have a HTML page code inside this variable in the following way:

$content = <<<HTML some html code in here HTML;

Now, within that HTML tag I wanted to add some PHP code, tried using <?php ..... ?>, however I wasn't successful with it. Can anyone help?

2

3 Answers 3

4

That's a HEREDOC syntax , The closing HTML; should be in margin else it wont work.

Valid Syntax

<?php
$somevar="Hello World";
echo <<<HTML
    <b> Hey this is some text and I am adding this variable $somevar</b>
HTML;

Invalid Syntax

    <?php
    $somevar="Hello World";
    echo <<<HTML
        <b> Hey this is some text and I am adding this variable $somevar</b>
      HTML; //<--- As you can see there is a leading space
Sign up to request clarification or add additional context in comments.

6 Comments

I am pretty sure that the tags are on the right place. The issue I am having is to add php code inside those HEREDOC tags (If that is what you call it)
I think you should also wrap your variables quotes {$somevar}
It is not just a variable that I want to add, perhaps I wasnt very clear, but I want to add few 5 php lines of code inside those HEREDOC tags
@Jordan, Please don't do that.. doing that so will eventually land yourself in Code Smell
@ShankarDamodaran thanks for the opinion, but there is no way to do it, because my <<<HTML tags contain entire HTML page, which is echo by php for display, but this time inside those HEREDOC codes I have html <select></select> tags, and the <option></option> tags content I want to fetch from my database using query
|
1

You can always use <script type="text/php">...</script>

1 Comment

I have tried that too, wasn't successful..Good thought anyways
1

With very old version of PHP, HEREDOC <<<HTML to open a string are not always supported. If you use an old PHP, a workaround is to do:

$myvar="some html code here <a href=\"eee\">link</a>
next line of html code
".$myotherphpvar."
rest of lines"

Note that if you open string with ", you must escape all " for html code with \.

With recent PHP version you can use HEREDOC syntax. This is example of syntax:

    $myvar=<<<HTML
some html code here <a href="eee">link</a>
    next line of html code $myotherphpvar
    rest of lines
HTML;

More examples on page: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

1 Comment

your example is clear when I want to add a variable inside the HEREDOC tags. However, in this occasion I want to add few 5 php lines of code inside those HTML HEREDOC tags, or if I can call a function inside those HEREDOC tags, then things can become easier

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.