Problem When Loading PHP File into Variable (Load Result of PHP Code Instead of the Code as a String)

Problem when loading php file into variable (Load result of php code instead of the code as a string)

<?php
$page_content = "./include/signup_content.php";
$page_header = "./include/signup_header.php";
include('master.php');
?>

and

<!DOCTYPE HTML>
<html>
<head>
<?php include $page_header; ?>
</head>

<body id="home">
<div class = "container">
<?php include $page_content; ?>
</div>
</body>
</html>

that's all

I hope that signup_content.php contains the similar template only

Render PHP file into string variable

As other people have mentioned output buffering is probably the cleanest solution here, because it allows you to separate your html template away from your logic. This way you end up with fairly readable html in your template file, instead of a spaghetti code mess.

function render_php($path)
{
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}

Then create your template file

//test.php
<?php for($i = 0; $i<5; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>

Then call your function:

render_php('test.php');

You could even make this more reusable by adding a second parameter (an array or object, i.e.

function render_php($path,array $args){
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}

Now lets see how this is useful

//create your template test.php
<?php for($i = $args['start']; $i<$args['end']; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>

Now create your arguments and pass them off to the render method

$args = array('start' => 0, 'end' => 5);
render_php('test.php', $args);

Why This is Useful

Now you have a reusable function that is useful, no matter how many arguments you need to pass, and your logic can be in a separate file from your display, making your code a lot more readable. We could use this to build large chunks of html that is still easy to read.

i.e.

$article = array(    //imagine we have an article that we have pulled from our database
'title' => 'Some Title',
'subtitle' => 'Some Sub Title',
'body' => 'lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
eu nulla quis ligula ornare ultricies. Vivamus malesuada lectus a mi
auctor pellentesque. Maecenas eu ultricies sapien, ac porta augue. ',
'image' => 'img/some_image.jpg'
);

echo render_php('article.php',array $article);

and create a template

<!-- article.php -->
<!DOCTYPE html>
<html>
<head>
<title><?php echo $article['title']; ?></title>
</head>
<body>
<img src='<?php echo $article['image']; ?>' alt='whatever' >
<h1><?php echo $article['title']; ?></h1>
<h2><?php echo $article['subtitle']; ?></h2>
<p><?php echo $article['body'];?></p>

</body>
</html>

require/include into variable

I've also had this issue once, try something like

<?php
function requireToVar($file){
ob_start();
require($file);
return ob_get_clean();
}
$test=requireToVar($test);
?>

fetch file with file_get_content and insert text into placeholder variables

If you have control over template.php and are aware of the security considerations, you're probably looking for include or require:

include('template.php');

Will do what you want to do.

EDIT

Output buffering

ob_start();
include('template.php');
$result = ob_get_clean();

Output buffering doesn't write PHP within HTML code when creating a new PHP file

The output buffer catches all output (echo, print, writes to stdout) after it. It doesn't disable the PHP's interpreter.

You have multiple options. For example:

1. Wrap the <?php tag.

<body>

<?php echo '<?php'; ?>
function display(){
...
}
<?php echo '?>'; ?>

</body>
</html>

This will run some PHP code that writes the string <?php. As you've noticed, you can run <?php ... ?> so that echo statement will work.

What follows—function display(){—is just plain text as it's not actually between <?php ... ?> tags at the moment, so PHP's engine ignores it.

Putting those values in variables and using short tags might make it easier to read:

$open = '<?php';
$close = '?>';

...

<?=$open?>
function display(){
...
}
<?=$close?>

2. Put the template in a separate file.

No need for an output buffer here.

$pagecode = file_get_contents('my-template-file.php');
fwrite($recipefile, $pagecode);

file_get_contents returns a plain string, as opposed to include.

3. Stop the PHP engine.

Note: Just because you can, doesn't mean you should (see below).

If you:

  • don't want to obscure the <?php tags (for example because you want your your editor to check or color highlight the syntax) and
  • you want to keep the code in one single file

then you can have PHP stop interpreting the rest of a file by calling __halt_compiler(), but you can't re-start the engine afterwards.

You could solve that problem by:

  1. putting the template at the end of the file,
  2. reading the entire file
  3. then splitting the code from the template.

// Just like the second example, read a PHP file (the current file) as a string.
$contentsOfCurrentFile = file_get_contents(__FILE__);

// Cut at this point.
$pagecode = substr($contentsOfCurrentFile, __COMPILER_HALT_OFFSET__ + strlen("?>\n"));

fwrite($recipefile, $pagecode);
fclose($recipefile);

// Below this point will be cut by the code above
// and then put into variable $pagecode.
// The ?> is not needed here, but we add it here
// (and stripped it) to keep syntax highlighting
// correct.
__halt_compiler();?>
This code is "not seen" by PHP
<?php echo 'Shows up as code in the variable'; ?>

Because __halt_compiler()'s use is rather rare and it can be confusing for other people, I would not recommend you use this.

Putting the code in a separate file like option 2, to me, seems the neatest way to go. You'll keep syntax highlighting in your text editor.

Option 1 leaves you with the option that if you need to, you can still write <?php ... ?> tags to execute code to make parts of the string dynamic.


Perhaps better still is a solution that doesn't need you to write separate files for every page. Why not make 1 file that gets a value (for example, from the URL with $_GET['page']) and loads the relevant content? Look into "rewrites" or "pretty URLs" to transform eg example.com/recipe-1 to example.com/index.php?page=recipe-1.

PHP file_get_contents with a php file

You just need to include() the PHP file.

Be wary of the security concerns.

If you want to capture the file's output, use output buffering.

include html code inside php with determine variable

You can use strtr for this. For e.g:

<?php

$a = 'Hi this is {name}. I am writing {language}';

echo strtr($a, ['{name}' => 'Abhishek', '{language}' => 'php']);

Strtr

In PHP, is there a way to capture the output of a PHP file into a variable without using output buffering?

A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.

For example:

// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;

// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar

How do I load a PHP file into a variable?

I suppose you want to get the content generated by PHP, if so use:

$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');

Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:

$Vdata = file_get_contents('path/to/YOUR/FILE.php');


Related Topics



Leave a reply



Submit