2008-10-05 57 views
44

我生成大量的XML,當用戶單擊表單按鈕時,將作爲後變量傳遞給API。我也希望能夠事先向用戶展示XML。如何將PHP輸出捕獲到變量中?

的代碼是一樣八九不離十結構如下:

<?php 
    $lots of = "php"; 
?> 

<xml> 
    <morexml> 

<?php 
    while(){ 
?> 
    <somegeneratedxml> 
<?php } ?> 

<lastofthexml> 

<?php ?> 

<html> 
    <pre> 
     The XML for the user to preview 
    </pre> 

    <form> 
     <input id="xml" value="theXMLagain" /> 
    </form> 
</html> 

我的XML正在與一些產生while循環之類的東西。然後需要在兩個地方顯示(預覽和表單值)。

我的問題是。我如何捕獲生成的XML在一個變量或任何東西,所以我只需要生成一次,然後打印出來,然後在預覽內生成它,然後再次在表單值內生成它?

ob_start();

而得到緩衝回:

回答

84
<?php 
ob_start(); 
?> 
<xml/> 
<?php 
$xml = ob_get_clean(); 
?> 
<input value="<?php echo $xml" ?>/> 
+14

@Jleagle $ XML = ob_get_clean()將返回輸出buffert和乾淨的輸出。它基本上執行ob_get_contents()和ob_end_clean() – jamietelin 2012-06-19 15:06:22

8

這聽起來像你想PHP Output Buffering

ob_start(); 
// make your XML file 

$out1 = ob_get_contents(); 
//$out1 now contains your XML 

注意,輸出緩衝停止傳到輸出,直到你「刷新」了。有關更多信息,請參閱Documentation

1

你可以試試這個:

<?php 
$string = <<<XMLDoc 
<?xml version='1.0'?> 
<doc> 
    <title>XML Document</title> 
    <lotsofxml/> 
    <fruits> 
XMLDoc; 

$fruits = array('apple', 'banana', 'orange'); 

foreach($fruits as $fruit) { 
    $string .= "\n <fruit>".$fruit."</fruit>"; 
} 

$string .= "\n </fruits> 
</doc>"; 
?> 
<html> 
<!-- Show XML as HTML with entities; saves having to view source --> 
<pre><?=str_replace("<", "&lt;", str_replace(">", "&gt;", $string))?></pre> 
<textarea rows="8" cols="50"><?=$string?></textarea> 
</html>