假设我在 PHP 中有这段代码来调用 Phantomjs
shell_exec("phantomjs a-phantomjs-file.js");
有没有办法将数据从 PHP 传递到 phantomjs 文件?也许某种命令行参数?
这里有 phantomjs 的命令行参数列表:https ://github.com/ariya/phantomjs/wiki/API-Reference
您可以使用字符串连接或插值从 PHP 传递它们,如果参数可能来自用户输入,请注意并小心防止注入攻击。
你也许可以做这样的事情。
$array = array("option1"=>"Test", "option2"=>"test2"); // this is what you want in phantom
$tmp = tempnam("/path/to/tempDir/", "PHANTOM_");
file_put_contents($tmp, "var params = ".json_encode($array)."; ".file_get_contents("a-phantomjs-file.js"));
shell_exec("phantomjs ".escapeshellarg($tmp));
unlink($tmp);
然后在幻像文件中,您可以访问属性
params.option1
我使用 PHP 向 PhantomJS 发送和接收数据,例如:
$command = '/path/to/phantomjs /path/to/my/script.js ' . escapeshellarg($uri);
$result_object = json_decode(shell_exec($command));
警告:确保不污染用户输入以防止其他人在您的服务器上执行代码!
在 javascript 中,此 URI 变量可用作system.args
数组的第二个元素(第一个元素是您正在调用的脚本的名称):
var system = require('system');
var uri = system.args[1];
当你的 javascript 完成后,你可以在退出 PhantomJS 之前输出一个 JSON 变量:
console.log(JSON.stringify({
"status": "success"
}));
phantom.exit();
在本例中 PHP 代码的第一行中,我们已经json_decode()
将纯文本 JSON 返回值解码为一个对象,因此在 PHP 中我们可以status
使用以下方法访问该变量:
print $result_object->status;