为什么file_get_contents在这个例子中没有正确加载phpscript?

时间:2013-03-21 08:24:58

标签: php javascript

我写了一些代码,实质上是做了以下几点:

<div id="thisDiv">
</div>

<?php
echo "<script>document.getElementById('thisDiv').innerHTML = '".addslashes(str_replace(array("\n", "\r"), "", file_get_contents('/path/to/file/example.php'')))."';</script>";
?>

但是,我注意到这不起作用:example.php中的<?php ?>标签中没有任何内容可以进入div。为什么这是他们的解决方法呢?

1 个答案:

答案 0 :(得分:1)

使用file_get_contents()时,如果您尝试在PHP脚本上使用它,则文件中的任何PHP都不会执行。如果要将PHP文件作为字符串返回,则一种方法是使用ob_*()函数:

ob_start();
include '/path/to/file/example.php';
$content = ob_get_contents();
ob_end_clean();

现在你可以使用$content这将是example.php,其中PHP被执行为字符串。