简体   繁体   English

CasperJS将数据传回PHP

[英]CasperJS passing data back to PHP

CasperJS is being called by PHP using an exec() command. PHP使用exec()命令调用CasperJS。 After CasperJS does its work such as retrieving parts of a webpage, how can the retrieved data be returned back to PHP? 在CasperJS完成其工作(例如检索网页的某些部分)之后,如何将检索到的数据返回给PHP?

I think the best way to transfer data from CasperJS to another language such as PHP is running CasperJS script as a service. 我认为将数据从CasperJS传输到另一种语言(如PHP)的最佳方法是将CasperJS脚本作为服务运行。 Because CasperJS has been written over PhantomJS, CasperJS can use an embedded web server module of PhantomJS called Mongoose. 由于CasperJS是通过PhantomJS编写的,因此CasperJS可以使用名为Mongoose的PhantomJS嵌入式Web服务器模块。

For information about how works the embedded web server see here 有关嵌入式Web服务器如何工作的信息,请参阅此处

Here an example about how a CasperJS script can start a web server. 这里有一个关于CasperJS脚本如何启动Web服务器的示例。

//define ip and port to web service
var ip_server = '127.0.0.1:8585';

//includes web server modules
var server = require('webserver').create();

//start web server
var service = server.listen(ip_server, function(request, response) {

    var links = [];
    var casper = require('casper').create();

    function getLinks() {
        var links = document.querySelectorAll('h3.r a');
        return Array.prototype.map.call(links, function(e) {
            return e.getAttribute('href')
        });
    }

    casper.start('http://google.fr/', function() {
        // search for 'casperjs' from google form
        this.fill('form[action="/search"]', { q: 'casperjs' }, true);
    });

    casper.then(function() {
        // aggregate results for the 'casperjs' search
        links = this.evaluate(getLinks);
        // now search for 'phantomjs' by filling the form again
        this.fill('form[action="/search"]', { q: 'phantomjs' }, true);
    });

    casper.then(function() {
        // aggregate results for the 'phantomjs' search
        links = links.concat(this.evaluate(getLinks));
    });

    //
    casper.run(function() {
            response.statusCode = 200;
            //sends results as JSON object
            response.write(JSON.stringify(links, null, null));
            response.close();              
    });

});
console.log('Server running at http://' + ip_server+'/');

You can redirect output from stdout to an array. 您可以将输出从stdout重定向到数组。

On this page it says you can do: 这个页面上它说你可以做:

string exec ( string $command [, array &$output [, int &$return_var ]] )

It goes on to say: 它继续说:

If the output argument is present, then the specified array will be filled with every line of output from the command. 如果输出参数存在,那么指定的数组将填充命令的每一行输出。

So basically you can do exec('casperjs command here, $array_here); 所以基本上你可以做exec('casperjs命令在这里,$ array_here);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM