2012-01-02 107 views
1

您好我想存儲一個dinamically生成(與PHP)的HTML代碼到一個變量,並能夠發送它作爲答覆一個AJAX請求。 比方說,我隨機生成類似的表:將html頁面存儲到一個php變量

<?php 
$c=count($services); 
?> 
<table> 
<?php 
for($i=0; $i<$c; $i++){ 
echo "<tr>"; 
echo "<td>".$services_global[$i][service] ."</td>"; 
echo "<td>".$services_global[$i][amount]."</td>"; 
echo "<td>&euro; ".$services_global[$i][unit_price].",00</td>"; 
echo "<td>&euro; ".$services_global[$i][service_price].",00</td>"; 
echo "<td>".$services_global[$i][service_vat].",00%</td>"; 
echo "</tr>"; 
} 
?> 
</table> 

我需要存儲所有生成的HTML代碼(其餘)和回聲它像一個JSON編碼變量:

$error='none'; 
$result = array('teh_html' => $html, 'error' => $error); 
$result_json = json_encode($result); 
echo $result_json; 

我可以也許生成一個HTML文件,然後用閱讀:

ob_start(); 
//all my php generation code and stuff 
file_put_contents('./tmp/invoice.html', ob_get_contents()); 
$html = file_get_contents('./tmp/invoice.html'); 

但它聽起來只是錯誤的,因爲我並不真的需要生成的代碼,但只將其發送到我的主頁作爲一個代表對ajax請求,這將是一種浪費資源。 有什麼建議嗎?

+0

我的建議:「請說一個更具體的問題」...... – rdlowrey 2012-01-02 20:20:27

+0

我也建議不要直接在代碼中生成html。最好使用某種模板引擎(只要php包含也可以)。我最喜歡的一個是Twig(http://twig.sensiolabs.org/) – petraszd 2012-01-02 20:29:28

回答

9

您不必將其保存到一個文件,你可以使用適當的輸出緩衝功能

// turn output buffering on 
ob_start(); 

// normal output 
echo "<h1>hello world!</h1>"; 

// store buffer to variable and turn output buffering offer 
$html = ob_get_clean(); 

// recall the buffered content 
echo $html; //=> <h1>hello world!</h1> 

More about ob_get_clean()

+0

問題是,如果我回顯html,那麼它將被視爲對ajax請求的回覆不是嗎?我需要生成的HTML沒有迴應它或類似的東西。 – g0dl3ss 2012-01-02 20:43:59

+0

您可以將html存儲在變量中並隨時使用它。你不必強迫它迴應,直到你需要它... – 2012-01-02 21:10:22

+0

爲了存儲html到內部緩衝區與ob_start();我需要生成並回應它。 – g0dl3ss 2012-01-02 21:22:38

0

如果數據是這麼多昂貴的再生,那麼我會建議你使用memcached

否則我會每次都重新生成它或將其緩存在前端。

0
for($i=0;$i<=5;$i++) 
{ 
    ob_start(); 
    $store_var = $store_var.getdata($i); // put here your recursive function name 
    ob_get_clean(); 
} 

function getdata($i) 
{ 
    ?> 
    <h1> 
    <?php 
     echo $i; 
    ?> 
    </h1> 
    <?php 
    ob_get_contents(); 
} 
相關問題