gpt4 book ai didi

php - 如何解决错误 QXcbConnection : Could not connect to display when using exec function for phantomJs using PHP

转载 作者:IT王子 更新时间:2023-10-29 01:03:22 26 4
gpt4 key购买 nike

我正在做一个我想同时使用 PHP 和 Phantomjs 的项目,我已经完成了我的 phantomJs 脚本并尝试使用 php exec 函数运行它。但该函数返回一个错误列表数组。下面我正在编写我的 phantomjs 和 php 代码

目录:/var/www/html/phantom/index.js

var page = require('webpage').create();
var fs = require('fs');

page.open('http://insttaorder.com/', function(status) {
// Get all links to CSS and JS on the page
var links = page.evaluate(function() {

var urls = [];

$("[rel=stylesheet]").each(function(i, css) {
urls.push(css.href);
});

$("script").each(function(i, js) {
if (js.src) {
urls.push(js.src);
}
});

return urls;
});

// Save all links to a file
var url_file = "list.txt";
fs.write(url_file, links.join("\n"), 'w');

// Launch wget program to download all files from the list.txt to current
// folder
require("child_process").execFile("wget", [ "-i", url_file ], null,
function(err, stdout, stderr) {

console.log("execFileSTDOUT:", stdout);
console.log("execFileSTDERR:", stderr);

// After wget finished exit PhantomJS
phantom.exit();

});

});

目录:/var/www/html/phantom/index.php

exec('/usr/bin/phantomjs  index.js 2>&1',$output);
echo '<pre>';
print_r($output);
die;

也试过

 exec('/usr/bin/phantomjs  /var/www/html/phantom/index.js 2>&1',$output);
echo '<pre>';
print_r($output);
die;

运行后出现以下错误

Array
(
[0] => QXcbConnection: Could not connect to display
[1] => PhantomJS has crashed. Please read the bug reporting guide at
[2] => and file a bug report.
[3] => Aborted (core dumped)
)

但是如果我像这样从终端运行 index.php 文件:

user2@user2-H81M-S:/var/www/html/phantom$ php index.php

然后它工作正常。我不知道如何解决它。请帮忙。

我正在使用以下版本

系统版本:Ubuntu 16.04.2 LTS
PHP版本:5.6
phantomJs版本:2.1.1

最佳答案

您是否尝试过在服务器上设置环境变量?或者在调用 phantomjs 之前添加它?

我遇到了同样的情况,找到了一些解决办法:

一个。将变量 QT_QPA_PLATFORM 定义或设置为 offscreen:

QT_QPA_PLATFORM=offscreen /usr/bin/phantomjs index.js

或将此行添加到您的 .bashrc 文件(放在末尾):

export QT_QPA_PLATFORM=offscreen

或者安装包 xvfb 并在 phantomjs 之前调用 xvfb-run:

xvfb-run /usr/bin/phantomjs index.js

或使用参数 platform:

/usr/bin/phantomjs -platform offscreen index.js

也许您不想/不能在您的服务器上进行修改,在这种情况下,您可以尝试从 official website 下载静态二进制文件。然后:

/path/to/the/bin/folder/phantomjs index.js

和/或在您的 .bash_aliases 文件中创建别名,如下所示:

alias phantomjs=/path/to/the/bin/folder/phantomjs

make sure that phantomjs is not installed already on the system if you decide to use the alias.

if the file .bash_aliases not exist already, feel free to create it or add the alias line at the end of the .bashrc file

一些引用资料:

关于php - 如何解决错误 QXcbConnection : Could not connect to display when using exec function for phantomJs using PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49154209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com