PHP 使用 proc_open() 函数调用 Chrome 渲染网页内容
在 Debian GNU/Linux 11 x86_64 上,你可以使用 PHP 函数 proc_open() 来调用谷歌浏览器,并通过渲染网页内容来输出网页内容。以下是一种实现的示例代码:
<?php
$descriptorspec = array(
0 => array('pipe', 'r'), // 标准输入
1 => array('pipe', 'w'), // 标准输出
2 => array('pipe', 'w') // 标准错误输出
);
$process = proc_open('google-chrome --headless --disable-gpu --print-to-pdf=- https://www.example.com', $descriptorspec, $pipes);
if (is_resource($process)) {
$content = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$return_value = proc_close($process);
if ($return_value == 0) {
echo $content;
} else {
echo 'An error occurred: ' . $error;
}
} else {
echo 'Failed to open process.';
}
?>
在上面的代码中,proc_open() 函数用于调用谷歌浏览器。google-chrome 是谷歌浏览器的可执行文件名,你可以使用 which google-chrome 命令来获取确切的可执行文件路径。--headless 选项用于在无头模式下运行浏览器,--disable-gpu 选项用于禁用 GPU 加速,--print-to-pdf=- 选项用于将网页内容输出为 PDF 格式。
stream_get_contents() 函数用于读取浏览器的标准输出和标准错误输出。最后,proc_close() 函数用于关闭进程。
请注意,为了使上述代码正常工作,你需要确保 Debian 系统上已安装谷歌浏览器,并且系统环境变量中包含 google-chrome 的可执行文件路径。你可以通过运行 which google-chrome 来获取确切的路径,并将其作为环境变量名传递给 proc_open() 函数。
原文地址: https://www.cveoy.top/t/topic/qkyW 著作权归作者所有。请勿转载和采集!