heredoc声明的问题

Adi*_*pta 3 php

我试图用heredoc语句替换HTML代码.但是,我在最后一行得到一个解析错误.我确信我没有在heredoc结束标记行上留下任何前导空格或缩进.以下是代码的一部分:

$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;
    ?>
Run Code Online (Sandbox Code Playgroud)

问题出在哪儿?除了上面我还有一个相关的问题.作为一种编码实践,最好是在整个过程中使用PHP代码,还是使用heredoc语法更好.我的意思是,在PHP模式下,脚本在HTML和PHP代码之间来回反弹.那么,哪种方法首选?

Gum*_*mbo 6

关于Heredoc语法PHP手册:

结束标识符必须从该行的第一列开始.

稍后在漂亮的红色警告框中:

请注意,具有结束标识符的行必须不包含其他字符,除了可能是分号(;)之外,这一点非常重要.这尤其意味着标识符可能没有缩进,并且在分号之前或之后可能没有任何空格或制表符.

所以你需要编写这样的代码以符合语法规范:

$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;
Run Code Online (Sandbox Code Playgroud)

如果你真的想要使用它,这取决于你.