How can I print each detail from Gelocation Codeigniter? - php

I am trying to retrieve my city visitor from my website using codeigniter
Here is code to show city
$city = $this->geolocation->get_city();
Here the output from geolocation is like
array(11) { ["statusCode"]=>string(2) "OK" ["statusMessage"]=> string(0) "" ["ipAddress"]=> string(12) "202.60.21.15" ["countryCode"]=> string(2) "ID" ["countryName"]=> string(9) "Indonesia" ["regionName"]=> string(10) "Jawa Timur" ["cityName"]=> string(11) "Pacarkeling" ["zipCode"]=> string(5) "60132" ["latitude"]=> string(6) "-7.258" ["longitude"]=> string(7) "112.758" ["timeZone"]=> string(6) "+07:00" } OK202.67.41.25IDIndonesiaJawa
I am using
$cities = json_decode($city, true);
foreach ($cities as $c) {
echo $c;
}
and the output is like this
OK202.67.01.25IDIndonesiaJawa TimurPacarkeling60132-7.258112.758+07:00
How can I get each data from the output? I want to print each data from Geolocation library in Codeingiter like
Your Visitor Country : Indonesia
Your IP Visitor : 202.67.01.25
Your City Name : Pacarkeling
Thank you very much :)

Are you asking for the keys of the array? If so, you can do something like this:
$city = $this->geolocation->get_city();
$city_info = json_decode($city, true);
foreach ($city_info as $key=>$value) {
echo 'Your ' . $key . ' : ' . $value . '<br>';
}

Related

Echo status message in php geonames timezone

I'm using following code php to get timezone:
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach($xml->children() as $timezone)
{
echo "TimezoneId: ".$timezone->timezoneId." ";
echo "DstOffset : ".$timezone->dstOffset." ";
echo "GmtOffset : ".$timezone->gmtOffset." ";
}
it work but for latitude and longitude of Antartica for example it give error status message:
<status message="no timezone information found for lat/lng" value="15"/>
How to echo this message?
I'm tryng this:
if ($xml->status) {
echo "error: ".$timezone->status['message']. "";
}
but don't work
You are trying to get an element from object, which doesn't exist. In such a XML element you have attributes and some values like in your case: countryCode, countryName, dstOffset, gmtOffset and etc. If you use var_dump() the result you can see the error message is in these attributes, which is an array.
Here you are an example:
var_dump() on a location without problem:
object(SimpleXMLElement)#4 (12) {
["#attributes"]=>
array(1) {
["tzversion"]=>
string(11) "tzdata2014i"
}
["countryCode"]=>
string(2) "KG"
["countryName"]=>
string(10) "Kyrgyzstan"
["lat"]=>
string(7) "40.4246"
["lng"]=>
string(7) "74.0021"
["timezoneId"]=>
string(12) "Asia/Bishkek"
["dstOffset"]=>
string(3) "6.0"
["gmtOffset"]=>
string(3) "6.0"
["rawOffset"]=>
string(3) "6.0"
["time"]=>
string(16) "2015-07-09 19:53"
["sunrise"]=>
string(16) "2015-07-09 05:41"
["sunset"]=>
string(16) "2015-07-09 20:36"
}
And here a var_dump() of Antartica:
object(SimpleXMLElement)#4 (1) {
["#attributes"]=>
array(2) {
["message"]=>
string(41) "no timezone information found for lat/lng"
["value"]=>
string(2) "15"
}
}
You can easily handle and print this error message like that:
if ($xml->status) {
echo 'error:' . $timezone->attributes()->message;
}
try this,
<?php
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach ($xml->geoname as $o_location){
printf(
'Name %s<br>
lat is %s<br>
lon is %s<br>
geonameId is %s<br>
countryCode is %s<br>
countryName is %s<br>
fcl is %s<br>
fcode is %<br>
',
$o_location->name,
$o_location->lat,
$o_location->lng,
$o_location->geonameId,
$o_location->countryCode,
$o_location->countryName,
$o_location->fcl,
$o_location->fcode
);
}
?>

How to iterate through this PHP array

I am retrieving information from the GetResponse Email Marketing API and my code returns this data from the array:
array(2) {
["zAuW"]=>
object(stdClass)#332 (7) {
["optin"]=>
string(6) "double"
["from_email"]=>
string(17) "email#gmail.com"
["name"]=>
string(23) "asw_getresponse_edition"
["description"]=>
NULL
["reply_to_email"]=>
string(17) "email#gmail.com"
["created_on"]=>
string(19) "2014-03-29 07:27:46"
["from_name"]=>
string(11) "1213456#"
}
["z1Bi"]=>
object(stdClass)#333 (7) {
["optin"]=>
string(6) "double"
["from_email"]=>
string(17) "email#gmail.com"
["name"]=>
string(7) "test"
["description"]=>
NULL
["reply_to_email"]=>
string(17) "email#gmail.com"
["created_on"]=>
string(19) "2014-03-29 02:54:51"
["from_name"]=>
string(11) "123456#"
}
}
object(stdClass)#330 (1) {
["zAuW"]=>
object(stdClass)#334 (7) {
["optin"]=>
string(6) "double"
["from_email"]=>
string(17) "email#gmail.com"
["name"]=>
string(23) "asw_getresponse_edition"
["description"]=>
NULL
["reply_to_email"]=>
string(17) "email#gmail.com"
["created_on"]=>
string(19) "2014-03-29 07:27:46"
["from_name"]=>
string(11) "123456#"
}
}
Here is the code used to get this data:
require_once('GetResponseAPI.class.php');
$api = new GetResponse('YOUR_API_KEY');
// Account
$details = $api->getAccountInfo();
//var_dump($details);
// Campaigns
$campaigns = (array)$api->getCampaigns();
$campaignIDs = array_keys($campaigns);
$campaign = $api->getCampaignByID($campaignIDs[0]);
var_dump($campaigns, $campaign);
I would like to know what PHP code could I use to loop through this array and display the information in a dropdown list. I have tried this but it is oviously wrong:
$output .= '<select class="asw_select'.$field_class.'" name="'.$this->prefix.'_options['.$id.']" id="'.$this->prefix.'_options['.$id.']">';
foreach($campaign as $key => $value)
$output .= '<option '.selected($current_mailing_list, $value['id'], false).' id="'.esc_attr($value['id']).'" value="'.$value['id'].'">'. __($value['name'], $this->prefix).'</option>';
$output .= '</select>';
Any help would be greatly appreciated.
You have an array of objects in your response. So, in your foreach loop you should access it's elements like $value->name (not as $value['name'])
You do not have id attribute for your values. So after above correction, $value->id will be empty. However the $key seems like a unique identifier for me. If this is the case, within your foreach loop you can replace $value->id with $key
$output.= '<select class="asw_select'.$field_class.'" name="'.$this->prefix.'_options['.$id.']" id="'.$this->prefix.'_options['.$id.']">';
foreach($campaign as $key => $value)
$output .= '<option '.selected($current_mailing_list, $key, false).' id="'.esc_attr($key).'" value="'.$key.'">'. __($value->name, $this->prefix).'</option>';
$output .= '</select>';

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

create ul and li using a multidimensional array in php

I have the following array:
$tree_array
When I do a var_dump, I get:
array(6) {
[0]=> string(23) "$100,000 Cash Flow 2013"
[1]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(13) "Sell Iron Oak" ["Opportunity"]=> string(13) "Sell Iron Oak"
[2]=> string(2) "10" ["OID"]=> string(2) "10"
}
[2]=> array(2) {
[0]=> string(32) "ask her if she would like to buy" ["Activity"]=> string(32) "ask her if she would like to buy"
}
[3]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(8) "Sell Car" ["Opportunity"]=> string(8) "Sell Car"
[2]=> string(2) "11" ["OID"]=> string(2) "11"
}
[4]=> array(2) {
[0]=> string(52) "Call Roy back to see if he would like to purchase it" ["Activity"]=> string(52) "Call Roy back to see if he would like to purchase it"
}
[5]=> array(1) {
["tot_opp"]=> NULL
}
}
My end goal is to create unordered lists and lists (ul, li) with this data. There will be more data added to the array as the database gets updated, so it will keep growing. My goal is to loop through the array and have it create the following code and be able to keep creating lists as the data grows. I am new to php and not sure how to accomplish this.
<ul>
<li>$100,000 Cash Flow 2013</li>
<ul>
<li>Sell Iron Oak</li>
<ul>
<li>ask her if she would like to buy</li>
</ul>
<ul>
<li>Sell Car</li>
</ul>etc...
Any help will be greatly appreciated! Thank you in advance!
You need a recursive function for that, not a loop. This way it will handle any depth of your source array.
function make_list($arr)
{
$return = '<ul>';
foreach ($arr as $item)
{
$return .= '<li>' . (is_array($item) ? make_list($item) : $item) . '</li>';
}
$return .= '</ul>';
return $return;
}
echo make_list($source_array);
Seems like a simple enough recursion to me:
function arrayToList($in) {
echo "<ul>";
foreach($in as $v) {
if( is_array($v)) arrayToList($v);
else echo '<li>' . $v . '</li>';
}
echo "</ul>";
}
It looks like you have some duplicate values up there. Are you using mysql_fetch_array? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.

How do I deal with these PHP objects?

I am using the Google map API V3 making a request with lat/lng, with the expectation of getting the full address data returned. However, my PHP program would fail to get, for example, the Zip Code returned sometimes. I did a var_dump of what's being returned. I see an extra object element, which may be the cause I'm not sure. It's entirely possible I don't know everything about how Objects in PHP work too. Here is the var_dump output for the area of interest. The first example does indeed return the Zip Code to my PHP program making the request while the second one fails to do so and gives an error of "Trying to get property of non-object...". Thanks in advance for taking a look on this and your useful comments.
This is the var_dump of $xml that is returned from Google Map API V3, which DOES NOT WORK and fails to return the zip code properly:
object(SimpleXMLElement)#1 (1) {
["Response"]=>
object(SimpleXMLElement)#2 (3) {
["name"]=>
string(24) "40.74005999,-73.99718229"
["Status"]=>
object(SimpleXMLElement)#3 (2) {
["code"]=>
string(3) "200"
["request"]=>
string(7) "geocode"
}
["Placemark"]=>
object(SimpleXMLElement)#4 (5) {
["#attributes"]=>
array(1) {
["id"]=>
string(2) "p1"
}
["address"]=>
string(38) "136 W 17th St, New York, NY 10011, USA"
["AddressDetails"]=>
object(SimpleXMLElement)#5 (2) {
["#attributes"]=>
array(1) {
["Accuracy"]=>
string(1) "8"
}
["Country"]=>
object(SimpleXMLElement)#8 (3) {
["CountryNameCode"]=>
string(2) "US"
["CountryName"]=>
string(3) "USA"
["AdministrativeArea"]=>
object(SimpleXMLElement)#9 (2) {
["AdministrativeAreaName"]=>
string(2) "NY"
["SubAdministrativeArea"]=>
object(SimpleXMLElement)#10 (2) {
["SubAdministrativeAreaName"]=>
string(8) "New York"
["Locality"]=>
object(SimpleXMLElement)#11 (2) {
["LocalityName"]=>
string(8) "New York"
["DependentLocality"]=>
object(SimpleXMLElement)#12 (3) {
["DependentLocalityName"]=>
string(9) "Manhattan"
["Thoroughfare"]=>
object(SimpleXMLElement)#13 (1) {
["ThoroughfareName"]=>
string(13) "136 W 17th St"
}
["PostalCode"]=>
object(SimpleXMLElement)#14 (1) {
["PostalCodeNumber"]=>
string(5) "10011"
}
}
}
}
}
}
}
["ExtendedData"]=>
object(SimpleXMLElement)#6 (1) {
["LatLonBox"]=>
object(SimpleXMLElement)#8 (1) {
["#attributes"]=>
array(4) {
["north"]=>
string(10) "40.7414089"
["south"]=>
string(10) "40.7387109"
["east"]=>
string(11) "-73.9958332"
["west"]=>
string(11) "-73.9985312"
}
}
}
["Point"]=>
object(SimpleXMLElement)#7 (1) {
["coordinates"]=>
string(24) "-73.9971822,40.7400599,0"
}
}
}
}
The above has these errors:
PHP Notice: Trying to get property of non-object in try.php on line 38
PHP Notice: Trying to get property of non-object in try.php on line 41
Here is the PHP code for those lines:
$status = $xml->Response->Status->code;
// Country
$country = $xml->Response->Placemark->AddressDetails->Country;
$country_code = $country->CountryNameCode;
$country_name = $country->CountryName;
// Address
$address_line = $xml->Response->Placemark->address;
// Street address
$Locality = $country->AdministrativeArea->Locality;
// var_dump($Locality);
$street = $country->AdministrativeArea->Locality->Thoroughfare->ThoroughfareName;
$city = $country->AdministrativeArea->Locality->LocalityName;
$state = $country->AdministrativeArea->AdministrativeAreaName;
$zip_code = $country->AdministrativeArea->Locality->PostalCode->PostalCodeNumber;
Line 41 is the last line of code with the $zip_code, and line 38 is the line of code which begins with $street.
You will notice the above contains a ["SubAdministrativeArea"]=> which the working example below does not. Does this matter?
object(SimpleXMLElement)#1 (1) {
["Response"]=>
object(SimpleXMLElement)#2 (3) {
["name"]=>
string(24) "40.74445606,-73.97495072"
["Status"]=>
object(SimpleXMLElement)#3 (2) {
["code"]=>
string(3) "200"
["request"]=>
string(7) "geocode"
}
["Placemark"]=>
object(SimpleXMLElement)#4 (5) {
["#attributes"]=>
array(1) {
["id"]=>
string(2) "p1"
}
["address"]=>
string(38) "317 E 34th St, New York, NY 10016, USA"
["AddressDetails"]=>
object(SimpleXMLElement)#5 (2) {
["#attributes"]=>
array(1) {
["Accuracy"]=>
string(1) "8"
}
["Country"]=>
object(SimpleXMLElement)#8 (3) {
["CountryNameCode"]=>
string(2) "US"
["CountryName"]=>
string(3) "USA"
["AdministrativeArea"]=>
object(SimpleXMLElement)#9 (2) {
["AdministrativeAreaName"]=>
string(2) "NY"
["Locality"]=>
object(SimpleXMLElement)#10 (3) {
["LocalityName"]=>
string(8) "New York"
["Thoroughfare"]=>
object(SimpleXMLElement)#11 (1) {
["ThoroughfareName"]=>
string(13) "317 E 34th St"
}
["PostalCode"]=>
object(SimpleXMLElement)#12 (1) {
["PostalCodeNumber"]=>
string(5) "10016"
}
}
}
}
}
["ExtendedData"]=>
object(SimpleXMLElement)#6 (1) {
["LatLonBox"]=>
object(SimpleXMLElement)#8 (1) {
["#attributes"]=>
array(4) {
["north"]=>
string(10) "40.7458050"
["south"]=>
string(10) "40.7431070"
["east"]=>
string(11) "-73.9736017"
["west"]=>
string(11) "-73.9762997"
}
}
}
["Point"]=>
object(SimpleXMLElement)#7 (1) {
["coordinates"]=>
string(24) "-73.9749507,40.7444560,0"
}
}
}
}
And here are the lines of code used to output which the $zip_code is blank for the first example, while with the second one it does work as expected.
echo "===================================\n";
echo "Status code is: " . $status . "\n";
echo "address line is:" . $address_line . "\n";
echo "=+=+=" . "\n";
echo "street is: " . $street . "\n";
echo "city is: " . $city . "\n";
echo "state is: " . $state . "\n";
echo "zip code is: " . $zip_code . "\n";
echo "country code is: " . $country_code . "\n";
echo "country name is: " . $country_name. "\n";
The different locations used in this example are both in New York City. I don't know why one is working while the other is not, expect I see it's returning the ["SubAdministrativeArea"]. Shouldn't the Google map API V3 return the same format of information for the same area? Is this even a factor in the problem I'm having? Am I not handling the objects and elements correctly? If so, please enlighten me because I am stuck at this point.
Or should I be checking for two different situations which might be returned (or more?) by the Google map API V3? Thanks!
You will notice the above contains a ["SubAdministrativeArea"]=> which the working example below does not. Does this matter?
Yes it matters.
Shouldn't the Google map API V3 return the same format of information for the same area?
Some elements of the answer will always be present at the same place in the result tree but some others depend on the request. I can't help you more on this as I never understood why there was sometimes more sublevels even if requests were very similar...
Is this even a factor in the problem I'm having?
Yes, because you can't rely on a fixed result structure.
Should I be checking for two different situations which might be returned (or more?) by the Google map API V3?
Another solution can be to use an other library than SimpleXML to handle the result, like DOM, which has functions to find children through a tree, like DOMElement::getElementsByTagName. Getting values needs a bit more coding than with SimpleXML but this way you don't need to check if there is a SubAdministrativeArea level or not.
I hope it helps.

Categories