vig*_*esh 1 php smarty youtube-api file-get-contents smarty2
我需要file_get_contents()在 smarty tpl 文件中使用 PHP 。我不能在 PHP 中使用它并将它分配给 smarty 模板。因为 URL 是通过 smarty 模板文件中的循环动态生成的。所以我使用 smarty 插件功能来完成这项任务。但我想知道是否有任何方法可以直接在模板文件中使用它,而不是从插件文件中解析它。
我附上了我用来实现这个功能的插件代码。请任何人让我知道如何直接在 smarty tpl 文件中使用它。
function smarty_function_getTitle($params)
{
if ($params['id']) {
$content = file_get_contents("http://youtube.com/get_video_info?video_id=".$params['id']);
parse_str($content, $ytarr);
return $ytarr['title'];
}
}
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码在 smarty 模板中调用它:
{getTitle id=$videoId}
Run Code Online (Sandbox Code Playgroud)
欢迎提出建议!
小智 5
对于那些没有阅读上述评论的读者,我自己和 OP 都知道这不是您使用模板引擎的方式。他似乎有自己的理由想要直接在模板中而不是插件中或在他的代码中提前执行此操作。因此,请不要因为我的演示方法而骂我 :)
以下是您在 Smarty 中的操作方法。
{"http://youtube.com/get_video_info?video_id=`$videoId`"|file_get_contents|parse_str:$result}
{$result.title}
Run Code Online (Sandbox Code Playgroud)
我在一个电话中完成了第一部分,但如果您想小心,您可以将其拆分为多个带有检查的电话。但是我在本地进行了测试,效果很好。