dpqy77560 2015-04-19 05:08
浏览 129
已采纳

PHP - 读取另一个PHP文件的内容而不回显

I am trying to reach the contents of a PHP file without the file actually outputting what it would usually do. Here is my test code:

File1 (test1.php)

<?php
    ob_start();
    include_once './test2.php';
    $test = ob_get_contents();

    echo $test;
?>

and here is file2 (test2.php)

<?php
     $testVar = 'Name!';
?>
<div class="testClass"><?php echo $testVar?></div>
<p>Spam2</p>

and I want it to only do this because of the

echo $test

line NOT because the file is outputting the content.

<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>

due to the echo, but it returns this

<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>
<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>

So how do I get it to only return the content once?

  • 写回答

2条回答 默认 最新

  • duanjunjie0196 2015-04-19 05:28
    关注

    Don't echo $test;. PHP is executing as it should. Since ./test2.php shows Spam in HTML it appears on the page, then you assign the page contents to a variable and echo it. What do you expect?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?