本教程指导如何在 php 中使用 php-node 模块调用 node.js 模块:安装 php-node 模块(通过 composer)。创建一个 node.js 模块并导出方法。在 php 中使用 nodeprocess 加载和调用 node.js 模块。实战案例展示了如何使用 php 从 excel 生成图表:node.js 模块读取 excel 数据并创建图表。php 代码通过 php-node 模块调用 node.js 模块生成图表。
如何使用 PHP 调用 Node.js 模块
在 PHP 中使用 Node.js 模块是一个强大且高效的方法,可以将两种语言的优势结合起来。本教程将逐步指导你如何实现这一点,并提供一个实战案例。
先决条件
- 已安装 PHP 7.4 或更高版本
- 已安装 Node.js 12 或更高版本
- 已安装 Composer(PHP 包管理器)
步骤 1:安装 PHP-Node 模块
在你的 PHP 项目中,通过 Composer 安装 PHP-Node 模块。
composer require "roave/php-node"
步骤 2:创建 Node.js 模块
在你的项目目录中创建一个新的 Node.js 模块,一个名为 example.js 的简单脚本如下:
立即学习“PHP免费学习笔记(深入)”;
// example.js
module.exports = {
helloWorld: () => "Hello World!"
};
步骤 3:使用 PHP 调用 Node.js 模块
在你的 PHP 代码中,使用 NodeProcess 类加载和调用 Node.js 模块。
use RoavePHPNodeNodeProcess;
// 加载 Node.js 模块
$process = new NodeProcess([
'scriptPath' => 'path/to/example.js'
]);
$process->start();
// 调用模块中的方法
$result = $process->invoke('helloWorld');
// 输出结果
echo $result; // Hello World!
实战案例:使用 PHP 从 Excel 生成图表
Node.js 模块:
// chart.js
const Excel = require('exceljs');
module.exports = {
createChart: async (inputFile, outputFile) => {
const workbook = new Excel.Workbook();
const sheet = workbook.addWorksheet('Sheet1');
// 从 Excel 文件读取数据
const data = await workbook.xlsx.readFile(inputFile);
// 创建表格
const table = sheet.addTable({
name: 'MyTable',
ref: 'A1:C10',
headerRow: true
});
// 创建图表
const chart = sheet.addChart('Chart1', {
title: 'My Chart',
type: 'line',
legend: {
position: 'bottom'
},
axes: [
{
title: 'x-axis',
type: 'number'
},
{
title: 'y-axis',
type: 'number'
}
],
series: [
{
name: 'Series 1',
visible: true,
marker: {
type: 'circle'
},
values: table.getColumn('C')
}
]
});
// 保存工作簿
return await workbook.xlsx.writeFile(outputFile);
}
};
PHP 代码:
// 加载 Node.js 模块
$process = new NodeProcess([
'scriptPath' => 'path/to/chart.js'
]);
$process->start();
// 调用模块中的方法
$inputFile = 'input-data.xlsx';
$outputFile = 'output-chart.xlsx';
$process->invoke('createChart', [$inputFile, $outputFile]);
// 输出结果
echo "Chart generated at $outputFile";
通过这种方法,你可以利用 PHP-Node 模块的强大功能,在 PHP 中轻松集成 Node.js 模块,构建更强大、更灵活的应用程序。