I want to print all info from geolocation API in codeigniter then I want to insert into database. I try to print using foreach but find an error,
$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']."
"; <-- EROR
echo "Cityname : ".$city['cityName']."
"; <-- EROR
}
Here is value of 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" }"
Eror if using foreach :
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: controllers/Front.php
Line Number: 105
Can you explain how to write right code to print each data. Thanks
You are getting response in array, replace this:
foreach ($city as $c) {
echo $c->regionName;
}
Into:
foreach ($city as $c) {
echo "Region :".$c['regionName'];
echo "Country code : ".$c['countryName']."
";
echo "Cityname : ".$c['cityName']."
";
}
Your $city
variable contains a json response. Decode it.
$city = json_decode($city, true);
You now have an array to loop through.