How to get the contents as a string?

Possible duplicate:
Run a PHP file and return the result as a string
PHP captures print / requires variable output

I am trying to get the contents of an include into a string. Is it possible?

For example, if I have a test.php file:

<?php echo 'a is equal to '.$a; ?> 

I need a function, say include_to_string, to enable test.php and return what will be displayed internally in the string.

Something like:

 <?php $a = 4; $string = include_to_string(test.php); // $string = "a is equal to 4" ?> 
+8
include php
source share
4 answers
 <?php ob_start(); include 'test.php'; $string = ob_get_clean(); 

I think this is what you want. See output buffering .

+28
source share
 ob_start(); include($file); $contents = ob_get_contents(); // data is now in here ob_end_clean(); 
+5
source share

You can do this by buffering the output :

 function include2string($file) { ob_start(); include($file); return ob_get_clean(); } 

@DaveRandom indicates (correctly) that the problem with the wrapper in the function is that your script ($ file) will not have access to the variable defined globally. This may not be a problem for many scripts included dynamically, but if this is a problem for you, then this method can be used (as others have shown) outside the shell of functions.

** Import Variables One thing you can do is add the dataset that you would like to present to your script variables. Think about how to pass data to a template.

 function include2string($file, array $vars = array()) { extract($vars); ob_start(); include($file); return ob_get_clean(); } 

You would call it this way:

 include2string('foo.php', array('key' => 'value', 'varibleName' => $variableName)); 

and now $key and $variableName will be visible inside your foo.php file.

You can also provide a list of global variables for "import" for your script, if that seems more understandable to you.

 function include2string($file, array $import = array()) { extract(array_intersect_key($GLOBALS, array_fill_keys($import, 1))); ob_start(); include($file); return ob_get_clean(); } 

And you would name it by providing a list of global characters that you would like to open with a script:

 $foo='bar'; $boo='far'; include2string('foo.php', array('foo')); 

foo.php should be able to see foo , but not boo .

+3
source share

You can also use this below, but I recommend this answer.

 // How 1th $File = 'filepath'; $Content = file_get_contents($File); echo $Content; // How 2th function FileGetContents($File){ if(!file_exists($File)){ return null; } $Content = file_get_contents($File); return $Content; } $FileContent = FileGetContents('filepath'); echo $FileContent; 

Function in the PHP manual: file_get_contents

0
source share

All Articles