How do I capture PHP output into a variable?

后端 未结 4 1772
猫巷女王i
猫巷女王i 2020-11-27 04:04

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 han

相关标签:
4条回答
  • 2020-11-27 04:42

    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>
    
    0 讨论(0)
  • 2020-11-27 04:47

    It sounds like you want PHP Output Buffering

    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 Documentation for more info.

    0 讨论(0)
  • 2020-11-27 05:01
    <?php ob_start(); ?>
    <xml/>
    <?php $xml = ob_get_clean(); ?>
    <input value="<?php echo $xml ?>" />͏͏͏͏͏͏
    
    0 讨论(0)
  • 2020-11-27 05:07

    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.php and the individual functions for more information.

    0 讨论(0)
提交回复
热议问题