我想添加几个我webscrap到最终结果数组的值。我废弃的每个值代表数组中的一列。
见下面我尝试的内容:
<?php
require_once 'vendor/autoload.php';
use Goutte\Client;
$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);
我的问题是单个结果不会被推送到数组。有什么建议吗?
有没有更好的方法可以向数组添加多个属性?
感谢您的回复!
答案 0 :(得分:2)
$结果在结束时是未知的。
尝试USE在filter-closure中包含外部变量$ result,如下所示:
$crawler->filter($coin)->each(function ($node) use (&$result) {
print $node->text()."\n";
array_push($result, $node->text());
});