1

私はphpが初めてで、簡単なスクリプトを作成しようとしています..しかし、私がやろうとしていることがob_start()で可能かどうかはわかりません。教えてください、ありがとう。ここに私のコードがあります:

<?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());
?>

それが私のコードの出力です:

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

ここに私が達成したいものがあります:

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

2 に答える 2

3

You need to output the PHP code, as opposed to running it. Treating it as a string will do that:

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

Now that the actual question is answered... It may be fun to control output buffering in this way, but it is probably not the best idea in the world, which is to say that there are better ways of achieving the same result. E.g. simply using an auxiliary variable, which holds the otherwise output buffered content, is a much saner approach:

$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 に答える