脚本宝典收集整理的这篇文章主要介绍了从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(); }); });
基本上我打开localhost地址,将页面内容切换到我的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.
>如果我从浏览器运行脚本,则在dock中看不到图标,因此服务器以其他方式启动.仍然没有回应,也没有pdf.
测试OSX 10.7,PHP 5.3.6,phantomjs最新.运行服务器的用户_www具有管理员权限,我正在写文件的文件夹被编译为777.
> phantomjs在前台启动,这意味着你的PHP脚本停止/睡眠直到phantomjs停止.启动phantomjs服务,或在后台运行它.有关HowTo的信息,请参阅“php execute a background process”.> Web服务器可能无法访问操作系统的“图形部分”,这意味着它无法与您的桌面交互.这就是为什么图标没有出现,但phantomjs应该仍然开始.
以上是脚本宝典为你收集整理的从php启动phantomjs服务器并等待它的响应全部内容,希望文章能够帮你解决从php启动phantomjs服务器并等待它的响应所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。