How to use ipinfodb to find country code only - php

I want to find the country code of my site visitor using the ipinfodb API.
When I try the following, http://api.ipinfodb.com/v3/ip-country/?key=<My_API_Key>&ip=<Some_IP>, it gives the following output:
OK;;<Some_IP>;US;UNITED STATES
How do I filter this output so that it shows only the country code ?
Regards,
Timothy
EDIT:
In reply to Charles,
After searching on google I came to know that the API can be given a 'format attribute as XML' so the following works.
$xml = simplexml_load_file('http://api.ipinfodb.com/v3/ip-country/?key=<My_API>&format=xml&ip=<Some_IP>);
echo $xml->countryCode;
How can I get the same output without the XML argument ?
Thanks

OK;;<Some_IP>;US;UNITED STATES
How do I filter this output so that it shows only the country code ?
I find it curious that you'd be able to invoke SimpleXML, but didn't think of explode, which will turn a string in into an array, splitting on the given delimiter. In this case, we need to explode on ;:
$string_data = 'OK;;127.0.0.1;US;UNITED STATES';
$sploded_data = explode(';', $string_data);
print_r($sploded_data);
echo "\nCountry code: ", $sploded_data[3], "\n";
This should emit:
Array
(
[0] => OK
[1] =>
[2] => 127.0.0.1
[3] => US
[4] => UNITED STATES
)
Country code: US
You may wish to review the rest of the string manipulation functions to see if there's any other interesting things you may have missed.

The above answer isn't particularly helpful, because the server output is only static if you explicitly specify the same IP address every time. If you hardcode a location request for a particular IP address, it's going to the be the same every time. What's the point?
Do this instead
Install the PHP class for their API. PHP Class
Play around with the PHP sample found here; save it as its own webpage and observe the results. Let's call it "userlocation.php." Please note that the fields will be null if you load from localhost.
Okay, the trick to parse this output is array_values(). Took me forever to figure this, but eventually I stumbled upon this.
So...
$locations = array_values($locations);
echo $locations[n],"<br />\n";
echo $locations[n+1],"<br />\n";
etc.
Whatever element you need, you can get in this way -- and it's dynamic. The code will return whatever country pertains to the user's IP address.
One last note. Take care to paste your API key into the class file and not into userlocation.php. The class file variables are protected, which is a good thing.
Anyway, I'm no expert; just thought I'd share what I've learned.

Related

Extract value from soap response

I need help to extract value from a soap response.
https://i.stack.imgur.com/djv5y.jpg
What i exactly need is:
$username=user
$message=success
Maybe include the SOAP response here, that would be helpful for those who come in the future. As for your question are you using a particular language? That would make it easier to answer.
If you are looking for a way to view use can use this URL: https://codebeautify.org/xmlviewer
Ok now that I see it, it's fairly easy
Assuming you have loaded the SOAP XML into a variable, lets call it $xml_string
$xml = simplexml_load_string($xml_string); // Load it as an object
$xmlarray = json_decode(json_encode($xml),TRUE); // Change it into an array
Then the variables you are looking for is in
$username = $xmlarray['UserName'];
$message = $xmlarray['response']['MESSAGE'];
BTW This solution is found here
PHP convert XML to JSON
I did it as an array as sometimes objects are a little hard to process. You can easily just do the first line and address it as an object. (If those are the only variables you need then an array works fine. Ex: the 'Plan' data will be messed up in an array as it appears twice)
There can be some issues such as the MESSAGE not appearing or the XML returning a failure but I think you should know how to code around missing datum.

Extracting e-mail address from a html structure using PHP

I am trying to modify a php file (It is of Joomla extension Community Builder 1.9.1, and the file is \components\com_comprofiler\plugin\templates\default\default.php), in order to extract the e-mail address from a variable.
For description’s sake, let’s say this variable is $html. To make sure this variable is the right one containing the e-mail address that I'm targeting, I insert:
<pre><?php print_r($html) ?></pre>
Into the file, and its output is the email address with a mailto link, and the corresponding HTML is something like
<span id="cbMa47822" class="cbMailRepl">myemail#yahoo.com</span>
So I guess I can use:
<?php $html_array = explode("\"",$html);echo $html_array[5]; ?>
Io get 'mailto:myemail#yahoo.com'; But actually it only returns a notice of:
undefined offset:5
So I print_r($html_array), and it return something like
Array
(
[0] => cbMa14768
[2] => class=
[3] => cbMailRepl
[4] => >...
)
It looks like the <a> tag part of the html output is replaced by "...", like what you see in Chrome’s developer tool html inspector, where before you expand it, the HTML looks like:
<span id="cbMa47822" class="cbMailRepl">...</span>
I looked deeper into the php code, trying to find out how this $html is contructed, but it is totally beyond my understanding.
For learning purpose, my questions are:
why there is no [1] in the result of print_r($html_array)
How do I test a variable’s value more exactly, by more exactly I mean totally without html input, like if the value is "foo", if should display the HTML as is, but not a link (when I use print_r, it returns a link)?
And most importantly, based on the information given above, can you give my any hint regarding how I can extract the e-mail address from a variable like this?
Finally, for those who are willing to take a deeper look into this, the variable I am talking about is $this->tableContent[$userIdx][1][6]->value in \components\com_comprofiler\plugin\templates\default\default.php, originally it wasn't in the code but I did some test and confirm it contains the email address. I inserted the following code between line 450 & 451
<?php $html_array = explode("\"",$this->tableContent[$userIdx][1][6]->value);echo $html_array[5]; ?>
To extract an e-mail address from an HTML strcuture as you describe, just use regex and preg_match:
$html = '<span id="cbMa47822" class="cbMailRepl">myemail#yahoo.com</span>';
preg_match("/mailto:(.*)\">/is", $html, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
The output would be:
Array
(
[0] => mailto:myemail#yahoo.com">
[1] => myemail#yahoo.com
)
So to access that e-mail address, just do this:
echo $matches[1];
The output would be:
myemail#yahoo.com
To avoid links you can use escape sequence.
you can use regular expression to match if the given string matches the email address pattern and print it
PHP has a vast support for functions which can perform wierdest tasks so search for them

preg_match ID in URL

Edit:
Sorry I wasnt very clear with my first post. Ok I have text stored in the database, Id like to process it and look for any links to the products on my site and turn them into a fancy link. Below is 2 links and my current exp. The second link (Link2) Works as expected and passes the value 21 to detailsLink() My problem lies with Link1 it passes the value of 2 to detailsLink() not 21 as expected. I want to disregard the url completely as detailsLink() recreates the link with the product rating/cat etc. It should also work on http or https links.
Link1: http://192.168.2.22/dev/details.php?id=21
Link2: http://192.168.2.22/dev/details.php?id=21&module=info#Desc
$s = preg_replace("%(?<![=\]\'\"\w])https?://[^<>\s\'\",]*$ADDRESS\/details\.php\?id=([0-9]+)[^<>\s\'\",]+%ie", "detailsLink(\\1)", $s);
the value of $ADDRESS is 192.168.2.22/dev
No need to reinvent the wheel:
$url="http://192.168.2.22/dev/details.php?id=21&module=info#Desc";
parse_str(parse_url($url,PHP_URL_QUERY), $arr);
print_r($arr);
gives you:
Array
(
[id] => 21
[module] => info
)
parse_str()
parse_url()
I don't understand. Why don't you just use $_GET['id']?
EDIT: Never mind. I never knew about those functions! (parse_url, that is)

How to convert a country string to its ISO 3166-1 code using Zend?

Does anybody know if it's possible to use Zend_Locale to get the ISO 3166-1 code for a country if you have the country name as a string?
For example I have "Nederland" so I would like to get "NL".
I don't know if Zend has something for that, but it's fairly easy to do on your own.
This tutorial shows how you can grab the latest list of ISO 3166-1 country codes in XML format, parse it, and then create a PHP file that can be included when you need a country code translation array:
$str = file_get_contents('http://opencountrycodes.appspot.com/xml/');
$xml = new SimpleXMLElement($str);
$out = '$countries'." = array(\n";
foreach ($xml->country as $country)
{
$out .= "'{$country['code']}' => \"{$country['name']}\",\n";
}
$out .= ");";
file_put_contents('country_names.php', $out);
Alternately, you can save it as a CSV file and load it using PHP's fgetcsv() function. That would probably be preferable IMO. Or, heck, you could just save the XML and parse it when you load it.
I'm not sure how within Zend HTTp calls can be made, but here is probably a good resource to refer.
Use Yahoo!'s Geo data, which allows mapping of free form strings into WOE Ids. For countries, WOE Ids are the ISO 3166-1 codes.
To convert a free form string into a WOE Id, you can use the GeoPlanet APIs : http://developer.yahoo.com/geo/geoplanet/
You should have a look at Zend_Locale::getTranslation(). You may get a list (a simple array) of country names - and then you may use array_search() to get the needed "country-key"!
I have made an up-to-date collection of countrynames and ISO 3166 country codes over at:
https://github.com/johannesl/Internationalization
You can use it to convert both name => country code and reverse.
I'm also creating a collection of common country aliases that will appear on github.

I need help parsing a PHP array for an embedded Google Calendar

I'm not sure I'm headed on the right path but what I want to do is have an embedded Google Calendar with multiple calendars encoded in the iframe source. Example:
<iframe src="https://www.google.com/calendar/embed?src=cjvssf4vj98hoa4os5hr26fmcg%40group.calendar.google.com&src=cjvssf4vj98hoa4os5hr26fmcg%40group.calendar.google.com"></iframe>
Notice the two sources (the resource IDs happen to be the same in this example, but in a real scenario they'd be different). What I want to do now is create an array that would let me put the name of the calendar and its resource ID. Example:
<?php $rsrcid = array('Some Calendar' => 'cjvssf4vj98hoa4os5hr26fmcg%40group.calendar.google.com',); ?>
And use this array to replace that chunk of src=, etc. so that it's easier to keep track of all these resource ID's (I plan on adding a few dozen). It would need to have concatenated to it the &src= to each line. No spaces. So that it's a long string that I can insert into the iframe src.
It should be noted I'm not at all good at writing my own PHP, so if I'm even thinking incorrectly please let me know. Does that make sense?
Thanks for reading.
I think I solved this with foreach:
<?php
foreach ($rsrcid as $name => $id){
echo '&src=' . $id;
}
?>
/noob

Categories