Categories
PHP

PHP assign contents of a script to a variable

Say you would like to include the content of script in your code.  By passing the variable to the script and returning this value, you can create a truly dynamic entry for your code, without any duplication of effort.

Here’s the breakdown:

  1. Use an output buffer
  2. Start the output buffer
  3. include the file with the passed variable
  4. store the buffered content in a variable
  5. stop the buffer.

Here’s the code:

ob_start(); // start buffer
include ("file-to-include.php");
$content = ob_get_contents(); // assign buffer contents to variable
ob_end_clean(); // end buffer and remove buffer contents
echo $content;

This example creates an xml playlist of mp3 and inserts the xml into a javascript:

<?php
ob_start(); // start buffer
include (DIR_FS_CATALOG . 'mp3_xml_gen_add.php');
$player_cue = ob_get_contents(); // assign buffer contents to variable
ob_end_clean(); // end buffer and remove buffer contents
?>

<script type="text/javascript">
var addFilesA = "";
<?php echo $player_cue; ?>
</script>