8
我想从我的php脚本运行一个phantomjs服务器,然后对它执行一个curl请求并读取它的响应(在最终版本中会给出生成的pdf的路径) 。从控制台运行phantomjs服务器文件,然后在浏览器中导航到它的地址时,一切正常。这就是server.js文件:从php启动phantomjs服务器并等待它的响应
var server, service, page = require('webpage').create(), address, output,
html = '<!DOCTYPE><html><head></head><body><h1>FOOO</h1></body></html>';
server = require('webserver').create();
var rasterize = function(html, callback){
address = 'http://localhost';
output = '/Users/me/print.pdf'
page.viewportSize = { width: 600, height: 600 };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function() {
page.content = html;
page.render(output);
callback();
}, 2000);
}
});
}
service = server.listen(8080, function (request, response) {
response.statusCode = 200;
rasterize(html, function(){
response.write('<h1>BAR</h1>');
response.close();
phantom.exit();
});
});
基本上我打开本地主机ADDRES,切换页面的内容,我的HTML字符串,然后保存渲染页面的PDF。
现在到了我的PHP脚本:
<?
function send_callback($data){
echo '{type: success, data: '.$data.'}';
}
function curl_post($url, array $post = NULL, array $options = array()) {
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if(! $result = curl_exec($ch)) {
trigger_error(curl_error($ch));
}
curl_close($ch);
send_callback($result);
}
shell_exec('phantomjs '.escapeshellarg(dirname(__FILE__).'/server.js'));
//wait to allow server to start
sleep(5);
$data = array('html'=> 'foo');
curl_post('http://localhost:8080', $data);
?>
也没有神奇的在这里。我在终端中执行phantomjs server.js
命令,并在5s(初始化服务器的时间)后对其执行curlPOST请求。
现在我有两种情况:
- 如果我运行从控制台的PHP脚本,用
php script.php
服务器开始,我可以看到进程的运行状态和图标在码头看到,但我从来没有得到任何回应它和pdf不会被创建。 - 如果我从浏览器运行脚本,图标在扩展坞中不可见,所以服务器以其他方式启动。仍然没有回应,也没有pdf。
任何人都可以在我的代码中看到任何错误或想到任何调试方法吗?
在OSX 10.7,php 5.3.6,phantomjs latest上测试。运行服务器的用户_www具有管理员权限,文件夹,我在写文件被chmoded 777
在调试方面,我首先输出/记录'shell_exec()'的输出 - 只需''echo'就足够了。第一步是使用CLI(即运行'php script.php'),然后从网络运行它。当你说“得不到回应”时 - phantomjs挂了吗?脚本是否退出或挂起?你可以手动在脚本启动的实例上运行phantomjs查询吗? – mjec