Skip to content
Advertisement

Adding multiple columns to array

I would like to add several values that I webscrape to a final result array. Each value that I scrape represents a column in the array.

See below what I tried:

<?php
require_once 'vendor/autoload.php';

use GoutteClient;

$client = new Client();
$cssSelector = 'tr';
$coin = 'td.no-wrap.currency-name > a';
$url = 'td.no-wrap.currency-name > a';
$symbol = 'td.text-left.col-symbol';
$price = 'td:nth-child(5) > a';

$result = array();

$crawler = $client->request('GET', 'https://coinmarketcap.com/all/views/all/');

$crawler->filter($coin)->each(function ($node) {
    print $node->text()."n";
    array_push($result, $node->text());
});

$crawler->filter($url)->each(function ($node) {
    $link = $node->link();
    $uri = $link->getUri();
    print $uri."n";
    array_push($result, $uri);
});

$crawler->filter($symbol)->each(function ($node) {
    print $node->text()."n";
    array_push($result, $node->text());
});

$crawler->filter($price)->each(function ($node) {
    print $node->text()."n";
    array_push($result, $node->text());
});

print_r($result); 

My problem is that the individual results do not get pushed to the array. Any suggestions why?

Is there a better method to add multiple attributes to an array?

I appreciate your replies!

Advertisement

Answer

$result is not known in your closure.

try USE to include the external variable $result within the filter-closure, like so :

$crawler->filter($coin)->each(function ($node) use (&$result) {
    print $node->text()."n";
    array_push($result, $node->text());
});

http://php.net/manual/en/class.closure.php

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement