如何将PHP输出捕获到variables中?

当用户点击一个表单button时,我产生了大量的XML,作为一个postvariables传递给一个API。 我也希望能够事先向用户展示XML。

代码在结构上类似于以下内容:

<?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在一个variables或任何东西,所以我只需要生成一次,然后只是打印出来,在预览内生成它,然后再次在表单值内?

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

把这个在你的开始:

  ob_start(); 

为了得到缓冲区:

  $ value = ob_get_contents();
 ob_end_clean(); 

有关更多信息,请参见http://us2.php.net/manual/en/ref.outcontrol.php和各个函数。;

这听起来像你想PHP输出缓冲

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

请注意,输出缓冲将停止发送输出,直到您“刷新”为止。 有关更多信息,请参阅文档 。

你可以试试这个:

 <?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>