PHP file rendering in a string variable

I need to display or evaluate a PHP file in a PHP string variable at runtime. file_get_contents () will read the content, but not evaluate the PHP code.

I am aware of the ob_start () solution (as described here: Get HTML rendering from a local PHP file ), but it looks pretty dirty. I hope for something more direct and clean.

An example of what I want to accomplish:

test.php

<?php

for ($i = 0; $ < 5; $i++) {
    echo '<p>' . $i . '</p>\n';
}

My code is:

<?php

$string = render_php('test.php');

/*
    Content of $string:
    <p>0</p>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p> 
*/
+4
source share
2 answers

, , , , html- . , html .

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

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

:

render_php('test.php');

, ( , ..

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

,

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

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

, , , , , . html, .

.

$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);

<!-- 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>
+13

:

test.php

<?php

function render_html(){
  $string = '';
  for ($i = 0; $i < 5; $i++) {
      $string .= '<p>' . $i . "</p>\n";
  }
  return $string;
}

:

<?php

include "test.php";
$string = render_html();

echo $string;
-1

Source: https://habr.com/ru/post/1622748/


All Articles