Variable Replacement PHP

By using this class we can replace the variables with the actual variables which you were getting dynamically.

First function is to get the path of the our template file.

Second function is to load the template file.

Third function is to get the text which we replaced.

Finally fourth function is to replace the variables with actual data.

Class file : parser.php
<?php
/**
 * This class will helpful for variable replacement from a loaded file
 *
 * @author Vikram Reddy
 * @version 1.0
 */
class Parser {
    public $dir = "";
    public $text = "";

    /**
     * To get directory location
     * @param $dir
     */
    function __construct($dir = "home/template") {
        $this->dir = $dir;
    }

    /**
     * To load the specified file from directory
     * @param $file
     */
   function loadFile($file, array $variables = null) {
      try {
      if (file_exists ( $this->dir . "/" . $file )) {

          // start output buffering
          ob_start();

          // create variables from the key/value pairs in the array
          if( is_array($variables) ) {
              extract($variables);
          }

          include_once $this->dir . "/" . $file;

          // store the output
          $this->text = ob_get_clean();

          // $this->text = file_get_contents ( $this->dir . "/" . $file );
      } else {
          throw new Exception ( $this->dir . "/" . $file . " does not exist" );
      }
  } catch ( Exception $e ) {
      error_log ( $e->getMessage () );
      die ();
  }
}

    /**
     * To get the text from a file
     * @return text
     */
    function getText() {
        return $this->text;
    }

    /**
     * To replace the variables
     * @param unknown_type $var
     * @param unknown_type $text
     */
    function replace($var, $text) {
        $this->text = str_replace ( "{\$$var}", $text, $this->text );
    }
}

?>

Post a Comment

Analytics