从get_file_contents中检索的文件内的Echo php变量

Yam*_*088 0 php

我试图让变量在用于唯一divID的模板文件中回显,但它不断输出整个字符串并忽略php标记.我的代码和结果如下:

comment.php:

<?php
ini_set("display_errors", TRUE);

$idOfContent = 1;
$numberOfComments = 4;

while($idOfContent<=$numberOfComments){
    $content = file_get_contents('comment_tmpl.php');
    echo $content;
    $idOfContent +=1;
}


?>
Run Code Online (Sandbox Code Playgroud)

comment_tmpl.php:

<div class="Container">
    <div class="Content" id="<? echo $idOfContent ?>">
        <div class="PhotoContainer"> Image here </div>
        <div class="CommentAndReplyContainer">
            <div class="CommentBox" id="TopCommentBox_<? echo $idOfContent ?>">
                <form method="post" action="comment.php">
                    <textarea name="comment" id="<? echo $idOfContent ?>_comment" onclick="this.value='';" > Write a comment </textarea>
                    <input type="hidden" name="buttonId" value="<? echo $idOfContent ?>" />
                    <input type="submit" id="submit" value="Post" />
                </form>
            </div>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

结果:

<div class="Content" id="<?php echo $idOfContent ?>"></div>

如何让它识别PHP标签并正确输出变量?

Ama*_*ali 5

file_get_contents()正如名称所示,该函数将获取内部的内容comment_tpl.php,echo将在HTML标记中输出它,但它将无法正确解析为PHP代码.我不确定你为什么要这样做,但你可能正在寻找include():

while($idOfContent<=$numberOfComments){
    include('comment_tmpl.php');
    $idOfContent +=1;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用eval(),但这是一个非常糟糕的主意,我不推荐它.