0

I can't seem to be able to display a response from my custom .proc file. I'm running php-phantomjs on laravel 5.6 on ubuntu. I've got a URL endpoint I'm using to invoke the custom file as follows:

public function getLinks()
{
    $location = base_path('phantom-scripts');


    $serviceContainer = ServiceContainer::getInstance();

    $procedureLoader = $serviceContainer->get('procedure_loader_factory')
        ->createProcedureLoader($location);

    $client = Client::getInstance();
    $client->getEngine()->setPath(\Config::get('phantomPath'));
    $client->setProcedure('my_procedure');
    $client->getProcedureLoader()->addLoader($procedureLoader);

    $request  = $client->getMessageFactory()->createRequest();
    $response = $client->getMessageFactory()->createResponse();

    $client->send($request, $response);
    dd($response->getContent());
  }

Here's the .proc file

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

console.log("loading...");



var url = 'http://www.example.com';

page.open(url, function (status) {

    if (status === "success") {

        var contentNeeded = page.evaluate(function () {
            return document.querySelector("h1").outerHTML;
        });


        console.log(contentNeeded);

    }


});


phantom.exit();

I'd like to display the 'contentNeeded' on my browser.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
andromeda
  • 4,433
  • 5
  • 32
  • 42

1 Answers1

1

PhantomJS exits too early in your script.

page.open calls are asynchronous (who knows how much time opening that url will take), so phantom.exit() runs right after the browser's only started opening that url. Instead exit PhantomJS after getting the info, in callback:

if (status === "success") {

    var contentNeeded = page.evaluate(function () {
        return document.querySelector("h1").outerHTML;
    });

    console.log(contentNeeded);
    phantom.exit();
}
Vaviloff
  • 16,282
  • 6
  • 48
  • 56
  • Tried it and still getting null as the result of the dd(). Is console.log the right way to print out / return content from the .proc file? – andromeda May 28 '18 at 11:30
  • 1
    Maybe not, I'm not very familiar with Laravel or Symphony — just pointed out a mistake that definitely would ruin your script if you did things right PHP-wise. – Vaviloff May 28 '18 at 14:49
  • dd() - dump and die - is simply a function that either does print_r for arrays or echo for variables then exits the php script. That said, I've moved away from the php-phantomjs wrapper and instead, I'll run exec() on the phantom script directly since I've found no recourse. Thanks for the input. – andromeda May 28 '18 at 15:30