How to run php code from file_get_contents or file in a function

妖精的绣舞 提交于 2019-11-26 21:34:11

问题


I am designing my own MVC pattern to ease the process of creating homepages. My templating system needs my controller class to output my views. This means I have to output the file through a php function. I have been searching for some a while now and can't seem to find a solution.

How can I, through a PHP function, run a string representing some source code ("< ?", "< ?php", "? >" and so on) as php? Eval would not take my < ? signs (and I read that function is crap for some reason).


回答1:


You could execute the php code and collect the output like this:

ob_start();
include "template.phtml";
$out1 = ob_get_clean();

http://www.php.net/manual/de/function.ob-get-contents.php




回答2:


Just include()ing the file instead should be fine. I've not dug that deeply into the source code but I'm fairly sure that's how Zend Framework implements templates.




回答3:


Replacing "echo file_get_contents()" with "include()" as GordonM suggested worked exactly as needed. can't upvote yet since I'm too new but for my needs this is the direct answer to the headlined question.




回答4:


Well, eval is not crap per se, it's just easy to create a security hole with that if you're not careful about what you allow inside that eval (that, and maybe the fact that it can be bad for readability of the code).

As for the <? signs, that's because eval expects php code, so if you wan't to mix php with plain output, include just the closing ?> tag.

In general however, you can implement templates in better fashion, try to look into output buffering.




回答5:


$code = '<?php
function GetBetween($content, $start, $end) {
  $r = explode($start, $content);
  if (isset($r[1])){
    $r = explode($end, $r[1]);
    return $r[0];
  }
  return '';
}';

function _readphp_eval($code) {
  ob_start();
  print eval('?>'. $code);
  $output = ob_get_contents();
  ob_end_clean();
  return $output;
}

print _readphp_eval($code);


来源:https://stackoverflow.com/questions/8472783/how-to-run-php-code-from-file-get-contents-or-file-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!