Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with heredoc statement [duplicate]

Tags:

php

I am trying to replace the HTML code with a heredoc statement. However, I am getting a parse error in the last line.I am sure that I have not left any leading space or indentation on the heredoc closing tag line.Following is a part of the code:

$table = <<<ENDHTML
    <div style="text-align:center;">
    <table border="0.5" cellpadding="1" cellspacing="1" style="width:50%; margin-left:auto; margin-right:auto;">
    <tr>
    <th>Show I.D</th>
    <th>Show Name</th>
    </tr>
    ENDHTML;
    while($row = mysql_fetch_assoc($result)){
            extract($row);
            $table .= <<<ENDHTML
            <tr>
                <td>$showid2 </td>
                <td>$showname2</td>
            </tr>
    ENDHTML;        
    }
    $table .= <<<ENDHTML
    </table>
    <p><$num_shows Shows</p>
    </div>
    ENDHTML; 
    echo $table;
    ?>

Where is the problem? I have a related question in addition to above. As a coding practice, is it better to use PHP code throughout or is it better to use a heredoc syntax. I mean, while in PHP mode, the script bounces back and forth between the HTML and PHP code. So, which is the preferred method?

like image 824
Adit Gupta Avatar asked Dec 28 '25 22:12

Adit Gupta


1 Answers

From the PHP manual about the Heredoc syntax:

The closing identifier must begin in the first column of the line.

And a little later in the nice red Warning box:

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.

So you need to write the code like this to comply with the syntax specification:

$table = <<<ENDHTML
    <div style="text-align:center;">
    <table border="0.5" cellpadding="1" cellspacing="1" style="width:50%; margin-left:auto; margin-right:auto;">
    <tr>
    <th>Show I.D</th>
    <th>Show Name</th>
    </tr>
ENDHTML;
    while($row = mysql_fetch_assoc($result)){
                extract($row);
                $table .= <<<ENDHTML
                <tr>
                        <td>$showid2 </td>
                        <td>$showname2</td>
                </tr>
ENDHTML;
    }
    $table .= <<<ENDHTML
    </table>
    <p><$num_shows Shows</p>
    </div>
ENDHTML;
    echo $table;

It’s up to you if you really want to use that.

like image 170
Gumbo Avatar answered Dec 31 '25 11:12

Gumbo



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!