0

I am trying to get the variables echoed inside a template file used for the unique div id's, but it keeps outputting the entire string and ignoring the php tags. My code and results are below:

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;
}


?>

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>

results:

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

How do I get it to recognize the PHP tags and output the variables correctly?

George Brighton
  • 5,131
  • 9
  • 27
  • 36
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • possible duplicate of [PHP sending variables to file\_get\_contents()](http://stackoverflow.com/questions/6905706/php-sending-variables-to-file-get-contents) – mario Oct 31 '13 at 20:19

1 Answers1

5

The file_get_contents() function will, as the name says, fetch the contents inside comment_tpl.php and the echo will output it in the HTML markup, but it won't be correctly parsed as PHP code. I'm not sure why you're doing this, but you're probably looking for include():

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

Alternatively, you could use eval(), but it's a very bad idea and I don't recommend it.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150