簡體   English   中英

在PHP代碼中使用php include

[英]Use php include within a php code

我有一個將創建txt文件的php代碼,我要添加的問題是txt文件的內容。

我想從外部文件中包含它。

這是我到目前為止使用的代碼:

<?php
$data = $_POST;
$time = time();
$filename_prefix = 'file/evidence_file';
$filename_extn   = 'txt';

$filename = $filename_prefix.'-'.$time.'-'.uniqid().'.'.$filename_extn;

if( file_exists( $filename ) ){
 # EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted
  $filename = $filename_prefix.'-'.$time.'-'.uniqid().'-'.uniqid().'.'.$filename_extn;
 # IMPROBABLE that this will clash now...
}

if( file_exists( $filename ) ){
 # Handle the Error Condition
}else{
  file_put_contents( $filename , '<?php include("text.php"); ?>' );
}
?>

問題是在當前代碼中使用php include! 它在txt文件中打印的全部是:

<?php include("text.php"); ?>

我怎樣才能顯示text.php的內容?

同樣,text.php文件包含php代碼。

如前所述,您可以使用file_gets_content來獲取文件的內容。

但是,如果您要首先執行文件(如php代碼),然后獲取結果內容並放入文件中(我想這就是您想要的),則必須使用緩沖區:

ob_start();

include('text.php');

$content = ob_get_contents();
ob_end_clean();

file_put_contents($filename , $content);

這樣,將執行php文件,並將其結果內容傳遞給該文件。 如果您想了解有關輸出控制功能的更多信息,請參見文檔

當前,您只是將一個字符串添加到file_put_contents ,因此它將直接使用您所輸入的內容,無論如何, include()仍然不是您想要的內容

include("text.php"); 加載php文件並在將其放入PHP時執行其內容,我認為您不想這樣做。 改用file_get_contents() ,如下所示:

file_put_contents($filename,file_get_contents("text.php"));

我想你應該那樣做

file_put_contents( $filename , '<?php '. file_get_contents("text.php") .'?>' );

file_get_contents函數以字符串形式返回文件內容include實際上包括並評估文件。 由於您的文件是PHP文件,並且您只想將其作為字符串包含在內,因此我的解決方案應該可以。

使用file_get_contents函數而不是include。

file_put_contents($filename, file_get_contents("text.php"));

當您要執行包含的代碼而不用作文本時,請使用include

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM