2017-12-06 28 views
-1

最終結果配列に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); 

私の問題は、個々の結果を配列にプッシュされませんということです。理由は何ですか?

複数の属性を配列に追加する方法がありますか?

返信いただきありがとうございます。

+1

あなたはこれで何を意味する: - '私の問題は、個々の結果が行うということです配列にプッシュされないでください.'あなたが得たアウトプットと予想されるoutocomeを表示してください(あなたの質問に両方を加えてください) –

答えて

2

$結果はあなたのクローズでは分かりません。

トライ使用は、フィルタ・クロージャ内の外部変数$結果が含まれるので、好きに:

$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

+1

あなたの答えは完璧です。しかし、imo [this link](http://php.net/manual/en/functions.anonymous.php)では、_use_キーワードについて説明しており、参照によって継承されていますが、クロージャーページよりも少し優れています。 – jh1711