Load file as string containing variable definitions

What I am trying to do in PHP is load a file containing php style variables and replace them with the contents of the variable. Here is my expample code not working the way I intend it.

module.html

<div class="module">
    $moduleText
</div>

      

index.php

<?php 
$moduleText = "Hello, World!";
$module = file_get_contents ( "module.html" );
echo $module;
?>

      

index.php Output

<div class="module">
    $moduleText
</div>

      

index.php Desired result

<div class="module">
    Hello, World!
</div>

      

Is there an easy way in PHP to get this desired result? I am building a CMS and this will do the inclusion of the module for me. Any help, snarky comments, or points in the right direction, greatly appreciated!

+3


source to share


3 answers


You can do this using the Heredoc chaining

Let me give you an example:

index.php

<?php 
$moduleText = "Hello, World!";
include "module.php";
echo $module;
?>

      



module.php

<?php 
$module = <<<EOD
<div class="module">
    $moduleText
</div>
EOD;
?>

      

You can do this in any loop and it will behave as expected.

Hope this helps!

+2


source


I created a templating system. The code should work if you copy and paste it following my sample directory structure.

Let me know if you have any questions or alternative ways to do this. I am always open to improvement. :)

Example directory structure:

- templates
---- index.html
---- module.html
- includes
---- functions.php
- index.php

      

index.html

<b>${myVariable}</b>
<div>
    ${module}
</div>

      

module.html:

<b>${foo}</b>
<i>${bar}</i>

      



functions.php:

<?php 

function getTemplate($file, $hooks){
    //Read our template in as a string.
    $template = file_get_contents($file);

    $keys = array();
    $data = array();
    foreach($hooks as $key => $value){
        array_push($keys, '${'. $key .'}');
        array_push($data,  $value );
    }

    //Replace all of the variables with the variable
    //values.
    $template = str_replace($keys, $data, $template);

    return $template;
}

?>

      

index.php:

<?php

require_once('includes/functions.php');

/* 
 * Load Modules First so we can get the 
 * contents as a string and include that string
 * into another template represented by a 
 * variable in the template such as 
 * ${module}
 */ 
$moduleHooks = array(
    'foo' => 'Oh fooey',
    'bar' => 'Chocolate Bar'
);
$moduleTemplate= 'templates/module.html';
$moduleText = getTemplate($moduleTemplate, $moduleHooks);

/*
 * Load the module you want to display. Be sure
 * to set the contents of the contents to a hook
 * in the module that we will display
 */
$indexHooks = array(
    'myVariable' => 'Index Variable',
    'module' => $moduleText 
);

$indexTemplate = 'templates/index.html';
$indexText = getTemplate($indexTemplate, $indexHooks);

/*
 * Finally Display the page
 */
echo $indexText;

?>

      

Output:

<b>Index Variable</b>
<div>
    <b>Oh fooey</b><i>Chocolate Bar</i>
</div>

      

The problem I ran into using was that when I used "include module.html;" I couldn't decide where to put this inside the index.html file unless I turned index.html into a php file.

0


source


Yes, it is possible, at this point , that all template libraries are a thing of the past.

For those looking for exactly this problem like me:

Load the file as a string containing variable definitions

The answer is pretty simple:

  • install the text file you want to output eg. html file
  • instead of your php vars write <?php echo $myvar ?>

    inside your file
  • set the php file with the above options and in the pane start output buffering , pick up the results and close the buffer as This answer suggests
  • to the same extent, use your collected results to do what you want, before submitting to withdrawal, and finally
  • don't forget to use the same variable names that will be used by the two files.

I will give an example with CSRF protection (!)

form.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Form Template</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/5.1.1/bootstrap-social.min.css" />
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-xs-offset-0 col-sm-8 col-sm-offset-2">
    <form method="POST" action="" novalidate="novalidate">
        <div class="form-group">
           <label for="email" class="control-label">Email</label>
           <div class="input-group">
              <label for="email" class="input-group-addon" aria-hidden="true"><i class="fa fa-at fa-lg"></i></label>
              <input type="text" class="form-control" id="email" name="email" value="" required="" title="Please enter your email" placeholder="example@gmail.com">
           </div>
           <span class="error help-block">Not acceptable domain</span>
        </div>
        <div class="form-group">
           <label for="password" class="control-label">Password</label>
           <div class="input-group">
              <label for="password" class="input-group-addon" aria-hidden="true"><i class="fa fa-lock fa-lg"></i></label>
              <input type="password" class="form-control" id="password" name="password" value="" required="" title="Please enter your password">
           </div>
           <span class="error help-block">Wrong password</span>
           <p><a href="/auth/newpass">Forgot password?</a></p>
        </div>
        <input type='hidden' name='csrf' value="<?php echo $arg[0] ?>">
        <button class="btn btn-primary btn-block">Sign in</button>
        <button class="btn btn-default btn-block">Cancel</button>
    </form>
</div>
</div>
</div>
</body>
</html>

      

Of particular interest is the line

<input type='hidden' name='csrf' value="<?php echo $arg[0] ?>">

      

template.php

session_start();
$csrf = $_SESSION['csrf']; //session stores the value
$arg = array($csrf);
ob_start();
   include './form.html';
   $include = ob_get_contents();
ob_end_clean();

// do whatever you want with $include

echo $include; // the page is rendered correctly!

      

We have achieved:

  • separation between client view and server code using
  • help clean interface to help relations between the two sides of the client and server, so developers do not need to know from php developer and vice versa (here I use the array $arg[n]

    to help them)
  • a great approach than the already existing php key function output_add_rewrite_var () as

    3.1. this meant solving another problem.

    3.2. it uses one buffer, whereas here we control the buffer and avoid the delay that one buffer introduces when repeating the page.

Hope this helps someone find this.

0


source







All Articles