Nasıl bir PHP bir dize olarak dahil tanımlarsınız?

6 Cevap php

Denedim:

$test = include 'test.php';

Ama bu sadece normalde dosyayı dahil

6 Cevap

Sen çıktı tamponlama işlevlerine bakmak isteyeceksiniz.

//get anything that's in the output buffer, and empty the buffer
$oldContent = ob_get_clean();

//start buffering again
ob_start();

//include file, capturing output into the output buffer
include "test.php";

//get current output buffer (output from test.php)
$myContent = ob_get_clean();

//start output buffering again.
ob_start();

//put the old contents of the output buffer back
echo $oldContent;

EDIT:

Jeremy işaret ettiği gibi, çıkış tamponlar yığını. Yani teorik gibi bir şey yapabilirsiniz:

<?PHP
function return_output($file){
    ob_start();
    include $file;
    return ob_get_clean();
}
$content = return_output('some/file.php');

Bu benim daha ayrıntılı özgün çözüm eşdeğer olmalıdır.

Ama bu bir test rahatsız değil.

Böyle bir şey deneyin:

ob_start();
include('test.php');
$content = ob_get_clean();

Eğer bu işlevi kullanabilirsiniz:

file_get_contents

http://www.php.net/manual/en/function.file-get-contents.php

[Benim en iyi çözüm]: Solution #1: yararlanın (bir işlev gibi çalışır) içerir

Index.php Dosya:

<?php
$bar = 'BAR';
$php_file = include 'included.php';
print $php_file;
?>

Included.php Dosya:

<?php
$foo = 'FOO';
return $foo.' '.$bar;
?>
<p>test HTML</p>

This will output FOO BAR, but Note: Works like a function, so RETURN passes contents back to variable (<p>test HTML</p> will be lost in the above)


Solution #2: file_get_contents ():

Index.php Dosya:

<?php
$bar = 'BAR';
$test_file = eval(file_get_contents('included.php'));

print $test_file;
?>

Included.php Dosya:

$foo = 'FOO';
print $foo.' '.$bar;

Bu irade çıkış FOO BAR, ama Note: include.php eval aracılığıyla çalışan gibi <?php açılış ve kapanış etiketleri () olmamalıdır


Solution #3: op_buffer (): [değil çözüm]

Index.php Dosya:

<?php
$bar = 'BAR';
ob_start();
include 'included.php';

$test_file = ob_get_contents();
print $test_file;
?>

Included.php Dosya:

<?php
$foo = 'FOO';
print $foo.' '.$bar;
?>
<p>test HTML</p>

Bu irade çıkış FOO BAR<p>test HTML</p> {[(1)];} bir çözüm olarak op_buffer düşündüren cevaplar rağmen, $ test_file için dahil dosya çıktı geçmek yapar, ancak dosyayı dahil olduğunda da çıktılar.

? Ben ob_ burada yanlış bir şey yapıyorum?