2013-01-15 29 views
2

想,如果我有有一個方法執行另一個PHP文件並返回方法的輸出,這可能嗎?

<?php 
function execute($filename){ 
    //do something 

    return $output; 
} 
?> 

,我也有另外一個PHP腳本executable.php

<?php 
    echo "I am executed"; 
?> 

然後我可以運行任何代碼EXCUTE第二個文件和PHP腳本test.php的當我撥打echo execute('executable.php');時,返回第一種方法execute的輸出?

我想你們可以理解我的意思。

+1

你可以使用輸出緩衝,但這種編碼有一個可怕的氣味。 – NullUserException

回答

2

您可以使用output buffering,只要被包含的文件已經不這樣做:

ob_start(); 

require $filename; 

$content = ob_get_contents(); 

ob_end_clean(); 

return $content; 
+0

感謝您的快速回答。讓我試試看,我會告訴你:) – prashu132

+0

我可以使用executable.php文件中的函數內定義的任何局部變量? – prashu132

+1

@ prashu132:是的。 – Ryan

0
<?php#test.php 
    include 'executable.php'; 
    echo $test; 
?> 

<?php#executable.php 
    $test = "I am executed"; 
?> 
+0

第二個文件將只是一個PHP文件。它不會將其所有輸出存儲在變量中。 – prashu132

+0

得到了我正在尋找的答案。 :)謝謝你試圖幫助我:) – prashu132

0
function execute($filename){ 
    include_once($filename); 
    } 

$ filename是文件將包含名稱..我認爲這將有助於你...

這是函數調用..

execute('abc.php'); 
+0

爲什麼不只是使用'include_once'?這真的不是什麼問題... – Ryan

+0

這是沒用的夥計。 @minitech給出了我正在尋找的答案。反正謝謝你的嘗試,幫助我:) – prashu132

2

使用ob_Start和​​捕獲腳本的輸出。這樣的東西應該工作:

<?php 

function execute($filename){ 
    ob_start(); 
    include $filename; 
    $output = ob_get_contents(); 
    ob_end_clean(); 
    return $output; 
} 
+0

感謝你太兄弟:) – prashu132

相關問題