执行一个PHP文件,并以字符串形式返回结果 [英] Execute a PHP file, and return the result as a string
问题描述
假设我有以下文件-template.php
:
<?php $string = 'Hello World!'; ?>
<html>
<head>
<title>Test Page!</title>
</head>
<body>
<h1><?= $string; ?></h1>
<p>You should see something above this line</p>
</body>
</html>
我知道我可以使用file_get_contents()
将文件的内容作为字符串获取,然后可以根据需要进行操作.但是,file_get_contents()
不执行PHP语句.
I'm aware that I can use file_get_contents()
to get the contents of the file as a string, which I can then manipulate as I require. However, file_get_contents()
doesn't execute PHP statements.
我已经成功地使用cURL来访问文件的呈现版本,但是它看起来相当缓慢且笨拙,这为页面的执行增加了相当多的时间-我想这是由于DNS查找正在执行.
I have successfully used cURL to get access to the rendered version of the file, but it seems rather slow and clunky, adding quite a fair amount of time to the execution of the page - which I would imagine is due to a DNS lookup being performed.
那么,如何在其中具有可用的PHP的情况下将template.php
的内容转换为字符串?
So, how can I get the contents of template.php
into a string - while having usable PHP there?
推荐答案
这应该做到:
ob_start();
include('template.php');
$returned = ob_get_contents();
ob_end_clean();
这篇关于执行一个PHP文件,并以字符串形式返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!