将食人反应数据推送到数组中,并将其传递以在laravel中查看 [英] Push the guzzle response data to array and pass it to view in laravel
问题描述
我可以通过控制器使用以下方法从网址中抓取数据:
I have the following method from my controller to scrap a data from a url:
public function fetchFromUrl(Request $request)
{
$a =[];
$goutteClient = new Client();
$guzzleClient = new GuzzleClient([
'timeout' => 60,
'verify' => false
]);
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://html.duckduckgo.com/html/?q=Laravel');
$crawler->filter('.result__title .result__a')->each(function ($node) use($a){
$parts = parse_url(urldecode($node->attr('href')));
parse_str($parts['query'], $params);
$url = $params['uddg'];
array_push($a, $url);
dump($url);
//$title = $node->text();
});
dump($a);
//return view('view')->withDatas($a);
}
执行上述方法后,我想将提取的数据$url
推送到数组$ a并将其传递给视图.但是我得到的只是一个空数组.
With the above method execution I want to push the extracted data $url
to the array $a and pass it to the view. But all I get is an empty array.
我也想将$title
推送到新数组并执行相同的操作.但是第一个无法正常工作,因此我已将其注释掉.
I also want to push $title
to new array and do the same. But the first one is not working so I've commented it out.
推荐答案
$a
数组正在多个范围内使用.当在内部范围"内使用时, (在each()
中)将其复制到函数中.目的是在内部范围"内通过引用利用$a
阵列.这是通过使用&符号&
The $a
array is being utilized within multiple scopes. When used within the "inner scope" (within each()
) it is copied into the function. The intent is to utilize the $a
array by reference within the "inner scope". This is completed by utilizing the ampersand &
$crawler->filter($filter_string)
->each(function($node) use ($a) {
...
可以替换为:
$crawler->filter($filter_string)
->each(function($node) use (&$a) {
这篇关于将食人反应数据推送到数组中,并将其传递以在laravel中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!