gpt4 book ai didi

php - 使用 PHP STDIN 和 proc_open 以及 Node JS 命令

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:09 25 4
gpt4 key购买 nike

我正在尝试使用一个名为 can-compile 的 Node js 包,它从 ejs 文件中读取内容,然后将数据转换为可用且 canjs 友好的输出。我试图避免将模板数据保存到服务器上的文件中并使用该文件来转换模板数据。这就是我一直尝试使用 php 的 STDIN/OUT 的地方。

编译器将模板文件的名称作为参数进行读取。我尝试了各种将模板数据传递到 Node 命令行的方法,但没有成功。

最终我想要实现的是能够将未编译的模板数据发送到 STDIN/OUT 管道,并让它从 can-compile Node 包返回编译后的代码。

有人可以指出我应该做什么的正确方向吗?这里我使用一个小模板示例(参见 $input)。但模板大小各不相同,最多可达数百行和字符。

$template_name = 'template_'.$template_data['name'].'.ejs';
$can_compiler = "/node_modules/can-compile/bin/can-compile --can 1.1.5 $template_name";
$input = "<img src="/media/<%==category.attrs.image%>" style="width:100%; height:100%;" />";
$cmd = sprintf("node %s",$can_compiler);

$descriptorspec = array(
0 => array('pipe','r'),
1 => array('pipe','w'),
2 => array('pipe','w')
);

$process = proc_open($cmd, $descriptorspec, $pipes);

if (is_resource($process)) {
fwrite($pipes[0], $input);
fclose($pipes[0]);

$template_content = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$error_content = stream_get_contents($pipes[2]);
fclose($pipes[2]);


$return_value = proc_close($process);

return $template_content;
}

我已经搜索了堆栈溢出并找到了这个 How to pass variables as stdin into command line from PHP 。我遇到的奇怪问题是我的代码昨天可以工作,但今天不行。也许一双新的眼睛可以帮助我。

最佳答案

我已经解决了这个问题,我在向管道发送数据时缺少 file_put_contents() 函数...

这是工作代码...

    $template_name = 'template_test.ejs';
$input = '<img src="/media/<%==category.attrs.image%>" style="width:100%; height:100%;" />';
$cmd = "node /node_modules/can-compile/bin/can-compile --can 1.1.5 $template_name";

$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w")
);

$process = proc_open($cmd, $descriptorspec, $pipes);

if (is_resource($process)) {

fwrite($pipes[0], file_put_contents($template_name,$input));
fclose($pipes[0]);

$template_name = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$return_value = proc_close($process);
echo $template_name;
}

关于php - 使用 PHP STDIN 和 proc_open 以及 Node JS 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34753273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com