【发布时间】:2021-06-01 18:19:52
【问题描述】:
我正在 webscraping 使用 php 中的 Goute Library 来自 this link 的表格。
下面是我的代码
$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>";
});
我的代码包含两个 foreach 循环。在第一个循环中,我声明了我想在第二个循环中访问的变量 $test 和 $country。
但是,每当我尝试访问变量时,我都会收到错误消息:
“未定义变量:测试”
为什么我无法访问这些已明确声明甚至初始化的变量?
【问题讨论】: