1

I'm new to php and trying to create a simple script.. but I don't know if what i'm trying to do is possible with ob_start() please let me know, thanks. here is my code:

<?php
ob_start();

if($mystuff !== 0) { foreach($mystuff['sirf7alk'] as $mystuff) {
?>

<?php include('header.php'); ?>

App name: <?php echo $mystuff->app; ?>

<?php include('footer.php');?>

<?php
} } 

file_put_contents('page.php', ob_get_contents());
?>

that's what my code outputs:

my header content
App name: My app name
my footer content

here is what i want to achieve:

<?php include('header.php'); ?>
App name: My app name
<?php include('footer.php');?>
4

2 回答 2

3

您需要输出PHP 代码,而不是运行它。将其视为字符串将执行此操作:

ob_start();
if ($mystuff !== 0) {
    foreach($mystuff['sirf7alk'] as $mystuff) {
        echo "<?php include 'header.php' ?>".PHP_EOL;
        echo "App name: {$mystuff->app}".PHP_EOL;
        echo "<?php include 'footer.php' ?>".PHP_EOL;
    }
}
$output = ob_get_contents();
file_put_contents('page.php', $output);

既然回答了实际问题……以这种方式控制输出缓冲可能会很有趣,但这可能不是世界上最好的主意,也就是说,有更好的方法可以达到相同的结果。例如,简单地使用一个辅助变量来保存原本输出的缓冲内容,这是一种更明智的方法:

$output = '';
if ($mystuff !== 0) {
    foreach($mystuff['sirf7alk'] as $mystuff) {
        $output .= "<?php include 'header.php' ?>".PHP_EOL;
        $output .= "App name: {$mystuff->app}".PHP_EOL;
        $output .= "<?php include 'footer.php' ?>".PHP_EOL;
    }
}
file_put_contents('page.php', $output);
于 2013-04-21T22:48:53.650 回答
0
<?php
ob_start();

if($mystuff !== 0) { foreach($mystuff['sirf7alk'] as $mystuff) {

echo "<?php include('header.php'); ?>\n";
?>
App name: <?php echo $mystuff->app; ?>

<?php
echo "<?php include('footer.php');?>\n";

} } 

file_put_contents('page.php', ob_get_contents());
?>

应该这样做。您必须将整个包含行作为字符串回显,以避免 php 解析它

于 2013-04-21T22:36:05.220 回答