2010-12-09 42 views
6

我有一個是我的控制頁面的輸出函數:PHP包括一個可變的內部

$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class='media-desc'>{$desc}</div>";

我想包括在定義的HTML中的文件「box.php」變量$page。我嘗試這樣做:

$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . include("box.php"); . "</div><div class='media-desc'>{$desc}</div>";

...但沒有奏效。我怎麼能把一個PHP包含在一個變量內?

回答

9

How can I put a php include inside of a variable?

# hello.php 
<?php 
    return "Hello, World!"; 
?> 

# file.php 
$var = include('hello.php'); 
echo $var; 

我一般會避免這樣的事情雖然。

3

首先,不要在語句中使用分號。
其次,將include語句包裝在括號中。

$page = "<div class='media-title'><h2>{$title}</h2></div> 
<div class='media-image'>{$image}</div><div class="inlinebox">" . 
(include "box.php") . "</div><div class='media-desc'>{$desc}</div>"; 

最後:在「box.php」文件,你需要做到以下幾點:

<?php 
ob_start(); 

// your code goes here 

return ob_get_clean(); 

編輯:PHP Manual - Return:關於調用函數比賽的外側返回一些信息。

+0

這將打開緩衝。也是一個好方法。 – santiagobasulto 2010-12-09 23:49:33

+0

我試過但沒有任何回報。爲了測試它,我把`<?php ob_start();回聲「測試」;返回ob_get_clean(); ?>`作爲我的box.php的內容,並沒有做任何事情。我刪除了ob_start和ob_clean,並輸出了「測試」一詞4次。標題兩次,一次高於應該有的地方,一次低於應該有的地方。 – mattz 2010-12-10 00:17:32

2

編輯:

不知道這是否是有用的,但我認爲,包括文件,以獲得一塊HTML的,是不是一個好的選擇。它不可擴展。你可以嘗試使用類似MVC的東西。你可以讓你的控制器重新渲染你想要的內容。

$view = $controler->getElement('box'); 

$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . $view . "</div><div class='media-desc'>{$desc}</div>"; 

試着解耦你的代碼。

我建議你看看一些MVC框架,在我看來,最好的一個是CakePHP。

+0

我同意你關於MVC,特別是CakePHP很棒。但在一些小型項目中(我想快速完成任務並轉移到酷炫的項目),我會使用HTML for HTML ......所有這一切,看起來像OP正在使用模板系統,因此這不是小項目,因此MVC肯定會有幫助,因此你會得到+1。 – Stephen 2010-12-10 00:03:32

+1

感謝您的回覆,但我認爲這有點凌駕於我的頭上。我確信這是一個非常好的方式,但我不知道你說的是什麼一半是:) – mattz 2010-12-10 00:14:14

13

php.net

// put this somewhere in your main file, outside the 
// current function that contains $page 
function get_include_contents($filename) { 
    if (is_file($filename)) { 
     ob_start(); 
     include $filename; 
     $contents = ob_get_contents(); 
     ob_end_clean(); 
     return $contents; 
    } 
    return false; 
} 

// put this inside your current function 
$string = get_include_contents('box.php'); 
$page = '<div class="media-title"><h2>{$title}</h2></div>'; 
$page .= '<div class="media-image">{$image}</div>'; 
$page .= '<div class="inlinebox">' . $string . '</div>'; 
$page .= '<div class="media-desc">{$desc}</div>';