如何将 PHP 输出捕获到变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/171318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:45:36  来源:igfitidea点击:

How do I capture PHP output into a variable?

phpxml

提问by Binarytales

I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.

我正在生成大量 XML,当用户单击表单按钮时,这些 XML 将作为 post 变量传递给 API。我还希望能够事先向用户显示 XML。

The code is sorta like the following in structure:

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

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

My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value).

我的 XML 是用一些 while 循环和东西生成的。然后它需要显示在两个地方(预览和表单值)。

My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?

我的问题是。如何在变量或其他任何内容中捕获生成的 XML,以便我只需要生成一次,然后将其打印出来,以便在预览中生成它,然后在表单值中再次生成它?

回答by moo

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

回答by Robert K

Put this at your start:

把这个放在你的开始:

ob_start();

And to get the buffer back:

并取回缓冲区:

$value = ob_get_contents();
ob_end_clean();

See http://us2.php.net/manual/en/ref.outcontrol.phpand the individual functions for more information.

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

回答by maxsilver

It sounds like you want PHP Output Buffering

听起来你想要PHP 输出缓冲

ob_start(); 
// make your XML file

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

Note that output buffering stops the output from being sent, until you "flush" it. See the Documentationfor more info.

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

回答by mattoc

You could try this:

你可以试试这个:

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