Change currency depending on country

2019-08-13 09:46发布

问题:

I have a package table. I want to change automatically the currency of each amount depending on the location of the user. For example, if the user is from UK, it will change to pounds, if from Australia it will be AUD. I have looked for a tutorial in google but all I can see is a conversion table, like this one not. How will I do this using HTML and javascript?

<style>
    td{
        text-align: center;
    }
</style>

<table>
    <tr>
        <td></td>
        <td>
            $100
        </td>
        <td>
            $200
        </td>
        <td>
            $300
        </td>
    </tr>
    <tr>
        <td>
            Package A
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
    </tr>
    <tr>
        <td>
            Package B
        </td>
        <td>
            <input type="checkbox" disabled/>
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
    </tr>
    <tr>
        <td>
            Package C
        </td>
        <td>
            <input type="checkbox" disabled/>
        </td>
        <td>
            <input type="checkbox" disabled/>
        </td>
        <td>
            <input type="checkbox" checked disabled/>
        </td>
    </tr>
</table>

回答1:

first, get the user's ip address

$ip =  $_SERVER['REMOTE_ADDR'];
echo $location = file_get_contents("http://api.hostip.info/country.php?ip=$ip");

it will echo the two letter country code of the user, if you will test it in your local host, replace the first line with this test ip

$ip = '121.1.11.166';

the test will echo 'PH' , meaning the ip of the user is from Philippines.

seen it here: link



回答2:

You may want to take look at Globalize.js which can handle many different formats including currency.

https://github.com/jquery/globalize

https://github.com/jquery/globalize/blob/master/doc/api/currency/currency-formatter.md

Those formats are based on different language settings which are available here https://github.com/jquery/globalize/blob/master/doc/cldr.md.

Using this you can even handle currency symbols but also display format of your data.

To get the language of your visitor you can use something like this

Var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

But keep in mind that one USD $ !== one Euro € ^^