2014-03-30 29 views
1

我怎樣才能返回大的HTML塊與一些PHP通過使用<<<HTML HTML;返回大的HTML塊與一些PHP沒有使字符串

return <<<HTML 
<div>Here some text</div> 
<?php thisFunctionEchosomthingNotReturn(); ?> 
<?php if($isflag){?> 
<span>DO not do this</span> 
<?php } ?> 
<?php echo $whatever; ?> 
HTML; 

我不明白什麼會工作,什麼不會!我應該如何使用這種返回<<<HTML HTML;塊與一些PHP變量,我需要回聲和一些函數,回顯一些事情(不返回)

+0

你有很多的語法錯誤,所以這將永遠不會工作。切勿將php標籤放入heredoc語句中。看到我的答案。它應該有所幫助。 –

+0

你可能會考慮學習使用PHP模板庫。他們可以更容易地格式化大量的輸出。哪一個使用?哦,親愛的,從哪裏開始?讓我數一下......; -/[Comparison_of_web_template_engines](http://en.wikipedia.org/wiki/Comparison_of_web_template_engines) –

回答

2

您可以使用「捕獲輸出」執行此任務。看到Output Control Functions

我有一些示例代碼,我剛剛測試過。它捕獲$ out1中div標記的輸出並稍後再顯示它。

此技術被用於許多'模板'庫和'框架'中的'視圖'。

<!DOCTYPE html> 
<html> 

<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Test of Output control functions</title> 
</head> 

<body> 
<?php ob_start(); // capture the buffer ?> 
    <div style="border: 4px solid red"> 
     <p>This is a test paragraph</p> 
     <p>This is test PHP code: <?php echo time(); ?></p> 
    </div> 
<?php $out1 = ob_get_contents(); // end capture ?> 

</body> 
</html> 


<?php echo $out1; // output now or save for later. ?> 
<?php var_dump($out1, strlen($out1)); ?> 
<?php exit; ?> 
+0

它的工作,非常感謝。 – zxprince

+0

不客氣。 :-) –

0

你不能寫HEREDOC語法內的控制結構/功能邏輯。

替代方式..

<div>Here some text</div> 
<?php thisFunctionEchosomthingNotReturn(); ?> 
<?php if($isflag){?> 
<span>DO not do this</span> 
<?php echo $whatever; }?> 
+0

那我該怎麼辦?我應該如何返回HTML和PHP函數,回聲一些HTML呢? – zxprince

+0

你知道PHP可以嵌入到HTML中嗎? http://www.php.net/manual/en/intro-whatis.php –

+0

是的,但我在這裏有一個情況。我需要返回一個大的HTML塊。但有一些函數不返回他們回顯一些HTML代碼。 – zxprince

0

我無法正確地理解你的問題可能是,這可能幫助:對於PHP

<HTML> 
<div>Here some text</div> 
<?php thisFunctionEchosomthingNotReturn(); 
if($isflag){?> 
<span>DO not do this</span> 
<?php }//Closing If if it ends here. 
echo $whatever; ?> 
</HTML> 
1

好吧,谷歌定界符。

但這是它是如何工作(我認爲你正在嘗試做的。

$html = <<<HTML 

<div> 
    <h1>$phpVariableTitle</h1> 
    <div> 
     {$thisFunctionEchosomthingNotReturn()} 
    </div> 
</div> 

HTML; 
return $html; 

嘗試。重要!定界符需要您關閉標籤被留下沒有標籤對齊。所以一定要確保有在你的heredoc標籤的左邊沒有空格或標籤,在這個例子中,我的heredoc標籤被稱爲HTML。另外,用大括號包裝你的php變量/函數是可選的,但是這種方法是很好的做法。

希望對您有所幫助

爲了使條件語句裏面工作,你需要使用的功能:

class My_Class { 
    public function myCondition($param) { 
     if($param === true) { 
     return '<p>True</p>'; 
     } else { 
     return '<p>False</p>'; 
     } 
    } 
} 
$object =new My_Class(); 
$html = <<<HTML 
    <div> 
     <h1>Conditional Statement</h1> 
     <div> {$object->myCondition(true)} </div> 
    </div> 
HTML; 

這樣的事情應該工作。但我沒有測試過它。

+0

請你能告訴我如何使用HEREDOC或其他方法嗎? – zxprince

+0

你不能。儘管你可以在循環中使用heredoc。if($ condition === true){//狀態1 HEREDOC在此處出現} else {//狀態2 HEREDOC在此處出現} –

+0

或者您可以在函數中使用條件語句並在HEREDOC語法中調用該函數。 –

相關問題