70

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.

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).

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?

Binarytales
  • 9,468
  • 9
  • 32
  • 38

5 Answers5

128
<?php ob_start(); ?>
<xml/>
<?php $xml = ob_get_clean(); ?>
<input value="<?php echo $xml ?>" />͏͏͏͏͏͏
moo
  • 7,619
  • 9
  • 42
  • 40
  • 19
    @Jleagle $xml = ob_get_clean() will return output buffert and clean output. It essentially executes both ob_get_contents() and ob_end_clean() – lejahmie Jun 19 '12 at 15:06
  • Don't forget to use `htmlentities($xml)`, or else your site will break if the xml has `"` in it. – kajacx Oct 20 '20 at 06:25
50

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.

Robert K
  • 30,064
  • 12
  • 61
  • 79
11

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.

maxsilver
  • 4,524
  • 4
  • 28
  • 24
3

When using frequently, a little helper could be helpful:

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;
    }
}
David Wolf
  • 1,400
  • 1
  • 9
  • 18
2

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>
mattoc
  • 692
  • 5
  • 6