【问题标题】:How do I capture PHP output into a variable?如何将 PHP 输出捕获到变量中?
【发布时间】:2010-09-15 08:08:50
【问题描述】:

当用户单击表单按钮时,我正在生成大量要作为 post 变量传递给 API 的 XML。我还希望能够事先向用户展示 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,因此我只需生成一次,然后将其打印出来,与在预览中生成它,然后在表单值中再次生成一样?

【问题讨论】:

    标签: php xml


    【解决方案1】:
    <?php ob_start(); ?>
    <xml/>
    <?php $xml = ob_get_clean(); ?>
    <input value="<?php echo $xml ?>" />͏͏͏͏͏͏
    

    【讨论】:

    • @Jleagle $xml = ob_get_clean() 将返回输出缓冲区和干净的输出。它本质上同时执行 ob_get_contents() 和 ob_end_clean()
    • 别忘了使用htmlentities($xml),否则如果xml中有",你的网站就会崩溃。
    【解决方案2】:

    把它放在你的开头:

    ob_start();

    并取回缓冲区:

    $value = ob_get_contents();
    ob_end_clean();

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

    【讨论】:

      【解决方案3】:

      听起来你想要PHP Output Buffering

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

      请注意,输出缓冲会阻止输出被发送,直到您“刷新”它。请参阅Documentation 了解更多信息。

      【讨论】:

        【解决方案4】:

        你可以试试这个:

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

        【讨论】: