如何在需要字符串时正确包含文件?

时间:2015-03-05 20:11:36

标签: php silex

我有一个本地文件,我需要包含在Silex应用程序的开头。我刚刚开始,我已经设置了所有锅炉板代码 - 特别是在这里。

// I need to return test.php for this route
$app = new Silex\Application();
$app->get('/', function() use($app) {
    return $string;  // put the file in a string
});
$app->run();

经过一些谷歌搜索后,我发现了这些文章:SOPHP.net

所以看起来我可以使用file_get_contents(),如果我需要评估代码,我可以将它包装在eval()中。或者我可以使用链接中显示的其他方法。

我希望只使用与require()类似的东西,但Silex需要返回一个字符串。我想我可以编写自己的辅助函数parseFile(),但这必须在其他地方完成吗?

更新

// this does not work, I'v verified the path is correct.
return file_get_contents($path, TRUE);

2 个答案:

答案 0 :(得分:0)

也许这个?

ob_start();
require 'somefile.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;

答案 1 :(得分:0)

文档有点难以浏览,但在这里它们是适当的锚 -

Sensio Labs Documentation

正如你所说,有一种更直接的方式。

您基本上需要使用恰当命名的sendFile()方法。

$app->get('/files/{path}', function ($path) use ($app) {
    if (!file_exists('/base/path/' . $path)) {
        $app->abort(404);
    }

    return $app->sendFile('/base/path/' . $path);
});
相关问题