我想在codeigniter中打印geolocation API中的所有信息,然后我想插入数据库。我尝试使用foreach打印但发现错误,
$ip='202.6x.xx.xx';
$this->load->library('Geolocation');
$this->load->config('geolocation', true);
$config = $this->config->config['geolocation'];
$this->geolocation->initialize($config);
$this->geolocation->set_ip_address($ip);
$country = $this->geolocation->get_country();
//var_dump($country);
$city = $this->geolocation->get_city();
if($city === FALSE){
//var_dump($this->geolocation->get_error());
}
else{
//var_dump($city);
foreach ($city as $c) {
echo $c->regionName; <-- EROR
}
echo "Country code : ".$city['countryName']."\n"; <-- EROR
echo "Cityname : ".$city['cityName']."\n"; <-- EROR
}
这是var_dump($ city)
的值string(286) "{ "statusCode" : "OK", "statusMessage" : "", "ipAddress" : "202.67.xx.xx", "countryCode" : "ID", "countryName" : "Indonesia", "regionName" : "regionblablabla", "cityName" : "cityblablabla", "zipCode" : "60132", "latitude" : "-7.258", "longitude" : "112.758", "timeZone" : "+07:00" }"
如果使用foreach,则会出错:
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: controllers/Front.php
Line Number: 105
您能解释如何编写正确的代码来打印每个数据。感谢
答案 0 :(得分:0)
您正在获取数组中的响应,请将其替换为:
foreach ($city as $c) {
echo $c->regionName;
}
分为:
foreach ($city as $c) {
echo "Region :".$c['regionName'];
echo "Country code : ".$c['countryName']."\n";
echo "Cityname : ".$c['cityName']."\n";
}
答案 1 :(得分:0)
您的$city
变量包含json响应。解码它。
$city = json_decode($city, true);
你现在有一个循环的数组。