I have a function like this:
public function handle()
{
News::truncate();
$client = new Client();
$crawler = $client->request('GET', 'features');
$crawler->filter('div[id=content]>.homefeature')->each(function ($node, $key) {
$title = $node->filter('.plain')->text();
$datepublished = $node->filter('.dateonline')->text();
$description = $node->filter('.teaser-link')->text();
$link = $node->filter('a')->link();
$link_r = $link->getUri();
if ($image = $node->filter('img')->count () > 0) {
$title = $node->filter('.plain')->text();
$datepublished = $node->filter('.dateonline')->text();
$description = $node->filter('.teaser-link')->text();
$link = $node->filter('a')->link();
$link_r = $link->getUri();
$image = $node->filter('img')->image();
$image_s = $image->getUri();
$image_s = preg_replace("/thumb_/", "", $image_s);
$filename = basename($image_s);
$image_path = ('news-gallery/' . $filename);
Image::make($image_s)->save(public_path('news-gallery/' . $filename));
$id = 1+ $key + 1;
$news = News::where('id', $id)->first();
// if news is null
if (!$news) {
$news = new News();
}
$news->title = $title;
$news->datepublished = $datepublished;
$news->description = $description;
$news->link = $link_r;
$news->image = $image_path;
$news->save();
$this->info('Main article ' .$title. ' done succesfully');
});
$crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) {
$title = $node->filter('.plain')->text();
$datepublished = $node->filter('.dateonline')->text();
$description = $node->filter('.teaser-link')->text();
$link = $node->filter('a')->link();
$link_r = $link->getUri();
$title = $node->filter('.plain')->text();
$datepublished = $node->filter('.dateonline')->text();
$description = $node->filter('.teaser-link')->text();
$link = $node->filter('a')->link();
$link_r = $link->getUri();
$image = $node->filter('img')->image();
$image_s = $image->getUri();
$image_s = preg_replace("/thumb_/", "", $image_s);
$filename = basename($image_s);
$image_path = ('news-gallery/' . $filename);
Image::make($image_s)->save(public_path('news-gallery/' . $filename));
//$id = 1+ $key + 1;
$newsArray[] = [
'title' => $title,
'datepublished' => $datepublished,
'description' => $description,
'link' => $link_r,
'image' => $image_path,
];
$this->info('Scraping done for ' .$title. ' succesfully');
});
print_r($newsArray);
//$news = News::insert($newsArray);
}
}
So I am trying to put everything into an array before saving it, however I get an error saying that $newsArray is undefined? if I put print_r inside the function, just below it I do get an output. How can this be solved? What I want to do is to loop throught each results as it does now, insert it into an array and later on, bulk insert it to db
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2eZPiL0
via IFTTT
Aucun commentaire:
Enregistrer un commentaire