Search code examples
phpapigouttelaravel-5.1

PHP return array when scraping with Goutte


I'm trying to return an array of items with goutte, I can print them out but I want them in an array, like an API. Here's the sample code. I'm using Laravel 5.1.

public function index()
{
    $posts = array();
    $client = new Client();
    $crawler = $client->request('GET', 'http://www.icetimux.com');

    $crawler->filter('h2 > a')->each(function ($node) use ($posts){
        // print $node->text(); //this prints them, needs to return as an array :(
        array_push($posts, $node->text());
    });
    return $posts;
}

All I get back is an empty array.


Solution

  • haha! I did it! check it out!

    public function index()
    {
        $client = new Client();
        $crawler = $client->request('GET', 'http://www.icetimux.com');
    
        return $result = $crawler->filter('h2 > a')->each(function ($node){
            return $posts[] = $node->text();
        });
    }