簡體   English   中英

PHP - 打開外部 php 文件並在瀏覽器中顯示

[英]PHP - open external php file and display in browser

我需要一個 php 腳本,它將打開一個外部 php 文件(來自同一個服務器文件夾),逐行瀏覽它,然后在瀏覽器中正常顯示頁面,就像直接打開外部 php 頁面一樣。

我需要逐行打開外部文件,以便在顯示之前對文件的內容進行一些處理。

我目前的代碼是:

<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
    // process the line here, and change if needed
    echo "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
?>

這有效,並且頁面被顯示,但是原始外部文件中的任何 php 代碼都不會被尊重——它被寫成文本,而不是由瀏覽器呈現。

我需要完全顯示外部文件,就像我自己打開文件(在本例中為“test.php”)一樣。

我在 SO 上看到的其他問題涉及一次打開或顯示完整文件,但我需要遍歷我的文件並首先對內容進行一些處理,因此需要逐行對其進行評估。

任何想法,將不勝感激。

謝謝

我會將更改保存到臨時文件中,然后將其包含在內。

<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
    // process the line here, and change if needed
    $newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}

// temporary file name
$temp_file = tempnam(sys_get_temp_dir(), 'myfile').".php";

// save modified code
file_put_contents($temp_file, $newCode);

// include modified code
include $temp_file;

// delete file
unlink($temp_file);

?>

檢索內容,處理它,將其保存在內存中,然后 eval() 它:

<?php

$newCode = "";
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {

    // process the line here, and change if needed
    //$line = myLineProcess($line);

    $newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}

//run the code
eval('?>'.$newCode.'<?php;');

?>

暫無
暫無

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

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