61

I'm a newbie to PHP/SQL and I am trying to use a variable within a heredoc as I need to output a lot of text. I've only included the first sentence as it is enough to show the problem).

My problem is that within the heredoc, the variables (see below: $data['game_name] and $data['game_owner']) are not recognized as variables, but as plain text. How can I solve this?

$response = $bdd->query('SELECT * FROM video_game');
while ($data = $response->fetch())
{

    echo <<<'EX'
    <p>Game: $data['game_name']<br/>
    the owner of the game is $data['game_owner']
    </p>
    EX;
}
3
  • 4
    you are using NOWDOC not HEREDOC Commented Jun 30, 2012 at 13:24
  • maybe a really dumb question, but does EX need to be left-justified? Commented Jan 1, 2021 at 18:13
  • @edwardsmarkf for many years already it doesn't. Commented Jul 21, 2022 at 5:34

1 Answer 1

140

Your heredoc needs a little modification (because it's actually Nowdoc!):

    echo <<<EX
    <p>Game: {$data['game_name']}<br/>
    the owner of the game is {$data['game_owner']}
    </p>
    EX;
  • Heredoc identifiers (unlike nowdoc ones) cannot be quoted. 'EX' needs to become EX.

    You're confusing Nowdoc with heredoc.

  • Complex data types in strings must be surrounded by {} for them to be parsed as variables. For example, $data['game_name'] should be {$data['game_name']}.

  • In the obsoleted PHP versions ( before PHP 7.3) the heredoc terminator must not have any preceding whitespace. From the documentation:

    The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.

You're mixing up heredoc and nowdoc here. You want to use heredoc and not Nowdoc because you've got variables inside your string. Heredocs are "extended" double quoted strings, whereas nowdocs are more akin to a single quoted string, in that variables are not parsed in nowdoc strings, but are in heredoc.

  • More on heredoc here.
  • More on Nowdoc here.

Please read the documentation more carefully on these.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.