Ubuntu环境下如何在PHP中集成jsreport?
在PHP中集成jsreport的方法
既然你已经用Node.js成功集成过jsreport,那你肯定知道它本质是个提供渲染服务的Node.js应用——PHP这边不需要复杂的本地集成,直接通过调用jsreport的HTTP API就能实现需求,下面是具体步骤和示例:
一、先确保jsreport服务正常运行
首先得保证你的jsreport服务处于启动状态,在终端执行:
jsreport start
默认情况下,jsreport会在http://localhost:5488提供服务,你可以访问这个地址确认服务是否正常。
二、PHP调用jsreport API的两种常用方式
方式1:直接传递模板和数据临时渲染
这种方式适合不需要复用模板的场景,直接把模板内容和数据传给jsreport渲染:
<?php // jsreport服务地址 $jsreportUrl = 'http://localhost:5488/api/report'; // 准备渲染所需的模板和数据 $renderPayload = [ 'template' => [ 'content' => '<h1>Hello {{username}}</h1>', 'engine' => 'handlebars', // 模板引擎,也可以用pug等 'recipe' => 'html' // 输出格式,可选pdf、docx、xlsx等 ], 'data' => [ 'username' => 'Dishi' ] ]; // 用原生cURL发送请求 $ch = curl_init($jsreportUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($renderPayload)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); // 执行请求并处理响应 $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($httpCode === 200) { // 如果是渲染PDF,可直接输出给浏览器下载 // header('Content-Type: application/pdf'); // header('Content-Disposition: attachment; filename="my-report.pdf"'); echo $response; } else { echo "渲染失败,错误信息:" . $response; } curl_close($ch); ?>
方式2:调用jsreport中已保存的模板
如果已经在jsreport控制台创建并保存了模板,直接用模板的shortid调用更方便,适合模板复用的场景:
<?php $jsreportUrl = 'http://localhost:5488/api/report'; // 替换成你自己的模板shortid(在jsreport控制台模板详情里能找到) $renderPayload = [ 'template' => [ 'shortid' => 'your-template-shortid-here' ], 'data' => [ 'username' => 'Jane Smith' ] ]; $ch = curl_init($jsreportUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($renderPayload)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($httpCode === 200) { // 示例:渲染PDF并在浏览器中预览 header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="saved-template-report.pdf"'); echo $response; } else { echo "渲染失败:" . $response; } curl_close($ch); ?>
三、进阶优化建议
- 用Guzzle替代原生cURL:如果你的项目已经引入了Guzzle HTTP客户端,代码会更简洁易维护,示例如下:
<?php use GuzzleHttp\Client; $client = new Client(); $response = $client->post('http://localhost:5488/api/report', [ 'headers' => ['Content-Type' => 'application/json'], 'json' => [ 'template' => ['shortid' => 'your-template-id'], 'data' => ['username' => 'Test User'] ] ]); if ($response->getStatusCode() === 200) { echo $response->getBody(); } ?>
- 添加认证支持:如果你的jsreport开启了基础认证,cURL可以添加
curl_setopt($ch, CURLOPT_USERPWD, '账号:密码');,Guzzle则在请求选项中加'auth' => ['账号', '密码']。 - 完善错误处理:实际项目中建议捕获cURL错误、解析jsreport返回的结构化错误信息,提升用户体验。
内容的提问来源于stack exchange,提问作者Dishi
相关产品推荐
相关产品推荐

