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

71

当用户点击一个表单按钮时,我正在生成大量XML并将其作为POST变量传递给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捕获到一个变量或其他位置,以便只需生成一次,然后将其打印出来,而不是在预览中再次生成,然后在表单值中再次生成?

5个回答

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

19
$xml = ob_get_clean()会返回输出缓冲区并清空输出。它实际上执行了ob_get_contents()和ob_end_clean()两个函数。 - lejahmie
不要忘记使用 htmlentities($xml),否则如果 xml 中有 ",您的网站将会瘫痪。 - kajacx

51

11
听起来你想要 PHP 输出缓冲
ob_start(); 
// make your XML file

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

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

3

在经常使用时,一个小帮手可能会有帮助

class Helper
{
    /**
     * Capture output of a function with arguments and return it as a string.
     */
    public static function captureOutput(callable $callback, ...$args): string
    {
        ob_start();
        $callback(...$args);
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
    }
}

2
你可以尝试这样做:
<?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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接