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

安稳与你 提交于 2019-11-27 23:42:28

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

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.

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.

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.

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