2011-01-25 71 views
3

是否可以將print()的輸出添加到變量中?PHP捕獲print/require變量輸出

我有以下情況:

我有一個PHP文件,該文件看起來是這樣的:

title.php

<?php 

$content = '<h1>Page heading</h1>'; 

print($content); 

我有一個PHP文件看起來像這樣:

page.php

<?php 

$content = '<div id="top"></div>'; 
$content.= $this->renderHtml('title.php'); 

print($content); 

我有一個函數renderHtml()

public function renderHtml($name) { 
    $path = SITE_PATH . '/application/views/' . $name; 

    if (file_exists($path) == false) { 
     throw new Exception('View not found in '. $path); 
     return false; 
    } 

    require($path); 
} 

當我轉儲page.php文件不包含title.php內容的內容變量。 title.php的內容只是在調用時纔打印,而不是添加到變量中。

我希望我很清楚自己想做什麼。如果沒有,我很抱歉,請告訴我你需要知道什麼。 :)

感謝您的幫助!

PS

我發現已經有像我這樣的問題了。但這是關於Zend FW的。

How to capture a Zend view output instead of actually outputting it

不過我想這正是我想做的事情。

我應該如何設置功能,使其表現如此?

編輯

只是想分享最終的解決方案:

public function renderHtml($name) { 
    $path = SITE_PATH . '/application/views/' . $name; 

    if (file_exists($path) == false) { 
     throw new Exception('View not found in '. $path); 
     return false; 
    } 

    ob_start(); 
    require($path); 
    $output = ob_get_clean(); 

    return $output; 
} 

回答

14

您可以捕獲輸出與ob_start()ob_get_clean()功能:

ob_start(); 
print("abc"); 
$output = ob_get_clean(); 
// $output contains everything outputed between ob_start() and ob_get_clean() 

另外,注意,你可以也從包含文件返回值,如函數:

a.php只會:

return "<html>"; 

b.php:

$html = include "a.php"; // $html will contain "<html>" 
+0

我將如何讓renderHtml功能的方式,我可以使用:`$這個 - > renderHtml( 'page.php文件');`這樣它會打印:`

頁標題

` – PeeHaa 2011-01-25 20:07:52

+0

Nvm明白了!感謝用戶! – PeeHaa 2011-01-25 20:09:51

2

您可以使用輸出緩存來捕捉任何輸出發送ob_start()​​。您使用ob_get_flush()http://us3.php.net/manual/en/function.ob-get-flush.php捕獲輸出。

或者你可以只返回標題的輸出。PHP的,像這樣:

<?php 

$content = '<h1>Page heading</h1>'; 
return $content;