dongxian5735 2015-09-09 10:17
浏览 41
已采纳

无法访问控制器中的变量(Laravel)

I'm using Laravel 5 with Goutte for crawling, and I'm trying to extract links that I need, not all links. So, basic regex comes to scene. Regex is ok, tested online and it's working, but when I try to apply that regex in controller I'm getting an error. Here is what I tried:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Goutte\Client;

class RvnController extends Controller
{
    public function index()
    {


        $client = new Client();

        $crawler = $client->request('GET', 'http://www.jgpnis.rs/index.php/red-voznje-preuzimanje-pregled.html');

        $regex_rvn_links = "/http:\/\/www.jgpnis.rs\/red_voznje\/([a-zA-Z0-9\-])+\/([a-zA-Z0-9\-\.])+/";
        $links_array = array();

        $crawler->filter('a')->each(function ($node) use($links_array) {

            if (preg_match($regex_rvn_links , $node->link()->getUri())) {
                $links_array[] = $node->link()->getUri();
            }


        });

        dd($links_array);
    }
}

And error is like : ErrorException in RvnController.php line 27: Undefined variable: regex_rvn_links.

Ok, I tried to pass that error applying regex directly in preg_match and it's working, but my $links_array is empty. To not be confused, if I print $node->link()->getUri() instead pushing it to array,I get about 15 links, so it's working. But then, I cant use it like this, I need that array. So, my question is how to use variables in this situations, because non of them is working. What I'm missing?

  • 写回答

1条回答 默认 最新

  • douyanlu7380 2015-09-09 10:44
    关注

    You are using closure, need to pass variables into the closure correctly.

    1) $regex_rvn_links must be passed into the closure. This is the cause of exception.

    2) $links_array must be passed by reference (&$links_array). This is why you got empty array.

    $crawler->filter('a')->each(function ($node) use (&$links_array, $regex_rvn_links) {
        if (preg_match($regex_rvn_links , $node->link()->getUri())) {
            $links_array[] = $node->link()->getUri();
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题