phplaravelgoutte

How do I access a variable in PHP inside a foreach loop?


I am webscraping a table from this link using the Goute Library in php.

Below is my code

    $client = new Client();
    $crawler = $client->request('GET', 'https://www.worldometers.info/world-population/population-by-country/');
    $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node) {

       $country = new Country(); // I have declared country here.
       $test = "TOday";   //I have a variable Test

        $node->filter('td')->each(function ($td,$i){

            switch ($i){
                case 1:
                    $country_name = $td->text();

                    echo $test; //I cannot access test here.
                    $country->name = $country_name; //I am not able to access the declared Country here

                    break;
                case 2:
                    //todo case 2
                    break;
                case 3:
                    //todo case 3
                    break;
                case 4:
                    //todo case 4
                    break;
            }
        });

        echo "<br><br><br>";

    });

My code contains two foreach loops. Inside the first loop I am declaring variable $test and $country which I would like to access inside my second loop.

However, whenever I try to access the variables, I am getting the error :

"Undefined variable: test"

Below is a screenshot from PhpStorm. enter image description here

Why am I not able to access these variables which have clearly been declared and even initialized?


Solution

  • if you want to access this variables iniside your function clouser, you should tell that function to use them:

     $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node)use( $country) {
    
       $country = new Country(); // I have declared country here.
       $test = "TOday";   //I have a variable Test
    

    if you have another vaiable you want to use, just add it to function argument:

    ->each(function ($node)use( $country,$secondVariable,$thirdVariable ...)