Problems with HEREDOC

I was a big fan of using PHP HereDoc strings but after having a few problems of uploading valid PHP HereDoc syntax to the server found that spurious trailing spaces were being added to HereDoc. HereDoc does not allow trailing spaces. It was not easy to find where the problem existed especially when misleading errors were reported :frowning:

I am now gradually replacing Heredoc with the following:

//=================================================
function OLD_render_group_image($group) : string {
    $html = <<<EOT
      <img src="/img/{$group['id']}.jpg">{$group['name']}</img>
EOT;

    return $html;
}

//=================================================
function render_group_image
(
  array $group
)
: string 
{
if( defined( DEBUG ) ):
  echo '<hr> DEBUG START' ;
  echo '<br> $group["id"]  ==> ' . $group["id"];
  echo '<br> $group["name"] ==> ' .$group["name"];
  echo 'DEBUG FINISH <hr>  ';
endif;

  $result = '<img src="/img/' 
          .  $group["id"]
          .  '.jpg">'
          .  $group["name"]
          . '</img>'
          ;

  return $result;
}

For what it is worth, I have never had any issues between production and development when using heredoc. I always concatenate my generated html into one long string. Having multiple echo’s scattered throughout the code just leaves me a bit queasy.

I’m not sure but think the spurious spaces get uploaded when using RSync

I don’t really see how that is possible. Heredoc is quite strict in that the ending EOT; has to start in the first column of it’s own line. To be honest, I’m not sure what “spurious trailing spaces” even means but again I don’t see how heredoc could be causing them.

Switching back and forth between php and templating can easily allow extra spaces to creep in. As can switching in and out of strings. Maybe some sort of operating system thing caused by newlines?

Might be interesting to open a new discussion and post an example.

Heredoc must finish on a new line and only have the name followed by a semicolon.

I have uploaded files with over one thousand lines and had trailing spaces after the semicolon. Error reporting does not pin point the problem and I’ve had to delete half the page to see if the error was in the first or second half, then delete half the problematic section again and again before the spurious spaces were found :frowning:

I have also never had problems with heredoc. The problem is not with Php. Nothing a little debugging cant uncover. Let us know what it was if you decide to dig into it. Don’t rewrite your code base because of it.

side note: up until PHP 7.3; from PHP 7.3 onward you can indent it if you like.
https://www.php.net/manual/en/migration73.new-features.php#migration73.new-features.core.heredoc