本教程指导如何在 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 模块。
|
1
|
composer require "roave/php-node"
|
步骤 2:创建 Node.js 模块
在你的项目目录中创建一个新的 Node.js 模块,一个名为 example.js 的简单脚本如下:
立即学习“PHP免费学习笔记(深入)”;
|
1
2
3
4
|
module.exports = {
helloWorld: () => "Hello World!"
};
|
步骤 3:使用 PHP 调用 Node.js 模块
在你的 PHP 代码中,使用 NodeProcess 类加载和调用 Node.js 模块。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
use Roave\PHPNode\NodeProcess;
$process = new NodeProcess([
'scrIPtPath' => 'path/to/example.js'
]);
$process->start();
$result = $process->invoke('helloWorld');
echo $result;
|
实战案例:使用 PHP 从 Excel 生成图表
Node.js 模块:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
const Excel = require('exceljs');
module.exports = {
createChart: async (inputFile, outputFile) => {
const workbook = new Excel.Workbook();
const sheet = workbook.addWorksheet('Sheet1');
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 代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
$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 模块,构建更强大、更灵活的应用程序。