Search code examples
phpreactphp

ReactPHP how can I get requested URL into a variable?


I need to parse some information from a bunch of sites and I have to have URLs from which I get the content. I use this library https://github.com/clue/reactphp-buzz . In this exsample i use only one URL. How can i get the URL which i send a request to?

  use Psr\Http\Message\ResponseInterface;


  $loop = React\EventLoop\Factory::create();
  $client = new Browser($loop);

  $client->get($url)
 ->then(function(\Psr\Http\Message\ResponseInterface $response) {
   $html = $response->getBody() . PHP_EOL;

  //here i need an url into a variable

  });

  $loop->run();

Solution

  • You can pass variables through to anonymous functions with the use-keyword.

    function(\Psr\Http\Message\ResponseInterface $response) use ($url) {
        // Now $url will be available inside the function
    }
    

    (notice the use before the opening brace)

    You can read more about it under Example #3 in the docs: https://www.php.net/manual/en/functions.anonymous.php