2008-10-05 33 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>