search
HomeBackend DevelopmentPHP TutorialLearn the internationalization function in PHP to view currency and date information

学习PHP中的国际化功能来查看货币及日期信息

做为一门在世界范围内广泛使用的编程语言,国际化能力往往是衡量一个编程语言是否能够大范围流行的重要内容。特别是对于 PHP 这种以 Web 页面编程为主战场的语言来说,国际化能力更是重中之重。在 PHP 中,已经为我们准备好了很多国际化相关的扩展及函数库,今天我们先来简单的学习一下,后面在学习到具体的 国际化与字符编码支持 相关的函数库时再进行深入的讲解学习。

获取当前浏览器用户的所在地

首先,我们来获取当前访问用户的所在地信息,也就是我们常见的 zh-cn 、 en-us 这类的地区语言编码信息。

// $_SERVER['HTTP_ACCEPT_LANGUAGE'] = zh-CN,zh;q=0.9;
$browserLocale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
print_r($browserLocale);
echo &#39;<br/>&#39;;
// zh

浏览器传递的这类区域信息是 zh-CN,zh;q=0.9; 这种形式的,我们可以通过 Locale::acceptFromHttp() 获得具体的区域信息。不过需要注意的是,不管是 zh-cn 还是 zh-tw ,返回的都是 zh ,而英文则会返回具体的是 en-us 还是 en-gd 之类的内容,也就是说这个函数对于我们中文语言的结果获取是有问题的。

$locale = [&#39;en&#39;, &#39;fr-FR&#39;, &#39;da, en-gb;q=0.8, en;q=0.7&#39;, &#39;zh-cn&#39;, &#39;zh-tw&#39;, &#39;en-us&#39;, &#39;en-ca&#39;, &#39;ja-jp&#39;];
foreach($locale as $code){
    print_r(Locale::acceptFromHttp($code));
    echo &#39;<br/>&#39;;
}
// en
// fr_FR
// da
// zh
// zh
// en_US
// en_CA
// ja_JP

我们可以手动来指定区域信息,可以看出除了 zh 之外其它的都是可以获取到正常的具体区域信息的。这点是我们使用这个函数时需要注意的地方。

获取指定地区所在地的标准数字信息

对于我们中国人来,数字比较习惯的是百、千、万位,一般也不太需要区分,而西方国家则喜欢三位一个逗号的分隔开来,也就是对应他们的英文数字习惯,比如 10000,在西方表示中是 10,000 ,英语是 ten thousand , 10000000 表示为 10,000,000 ,英语是 ten million 。因此,在 PHP 中,也是有相对于这种情况的数字表示形式,也就是为普通数字加上逗号以表示西方数字标准格式。

$locale = [&#39;en&#39;, &#39;fr-FR&#39;, &#39;en-gb&#39;, &#39;zh-cn&#39;,&#39;en-us&#39;, &#39;ko-kr&#39;, &#39;ja-jp&#39;];
$money = 1234567.89;
foreach($locale as $code){
    $numberformat = new NumberFormatter($code, NumberFormatter::DECIMAL);
    echo $code, ":";
    echo $numberformat->format($money), &#39;, &#39;;
    echo $numberformat->parse($numberformat->format($money)), &#39;<br/>&#39;;
}
// en:1,234,567.89, 1234567.89
// fr-FR:1 234 567,89, 
// en-gb:1,234,567.89, 1234567.89
// zh-cn:1,234,567.89, 1234567.89
// en-us:1,234,567.89, 1234567.89
// ko-kr:1,234,567.89, 1234567.89
// ja-jp:1,234,567.89, 1234567.89

我们直接使用 format() 方法,就可以获得指定地区的标准数字表示形式。可以看出亚洲地区的都是和欧美国家相同的,但法国则是使用空格进行分隔的。

获取指定地区所在地的货币符号信息

既然有数字格式的不同了,那么货币形式的区别就也是类似的形式了,只不过我们在使用 NumberFormatter 类的时候需要指定后面的数字类型常量为货币形式 NumberFormatter::PERCENT 。

oreach($locale as $code){
    $numberformat = new NumberFormatter($code, NumberFormatter::PERCENT);
    echo $code, ":";
    echo $numberformat->format($money), &#39;<br/>&#39;;
}
// en:¤1,234,567.89
// fr-FR:1 234 567,89 €
// en-gb:£1,234,567.89
// zh-cn:¥1,234,567.89
// en-us:$1,234,567.89
// ko-kr:₩1,234,568
// ja-jp:¥1,234,568

看出来了吗,当指定了货币形式后,format() 出来的结果直接就带上了货币符号。第一个 en 的货币符号其实就是国际通用货币符号,而日元和我们人民币的符号是相同的,这也是一个有趣的历史知识,大家可以自行查询下。

获取指定地区所在地的完整日期

最后就是获取的各地的日期标准格式。其实现在大家通用的都是 yyyy-mm-dd 这种形式来表示日期,不过正式规范的日期标准格式各个地区还是有所不同的。

$date = &#39;2020-09-25 11:05:22&#39;;
foreach($locale as $code){
    $l = new Locale($code);
    
    $d = new IntlDateFormatter($code, IntlDateFormatter::FULL, IntlDateFormatter::FULL);
    $c = IntlCalendar::createInstance(NULL, $code);
    $c->set(&#39;2020&#39;, &#39;09&#39;, &#39;25&#39;, &#39;11&#39;, &#39;22&#39;, &#39;33&#39;);
    echo $code, ":";
    echo $d->format($c), "<br/>";
}
// en:Friday, September 25, 2020 at 2:48:12 PM China Standard Time
// fr-FR:vendredi 25 septembre 2020 à 14:48:12 heure normale de la Chine
// en-gb:Friday, 25 September 2020 at 14:48:12 China Standard Time
// zh-cn:2020年9月25日星期五 中国标准时间 下午2:48:12
// en-us:Friday, September 25, 2020 at 2:48:12 PM China Standard Time
// ko-kr:2020년 9월 25일 금요일 오후 2시 48분 12초 중국 표준시
// ja-jp:2020年9月25日金曜日 14時48分12秒 中国標準時

是不是很方便,直接就以当地的语言来表示指定地区的标准日期格式了。

推荐学习:《PHP视频教程

总结

对于跨境项目来说,这些功能是非常重要的能力,能够帮助我们快捷地开发或切换相关的地区,等到深入学习的时候再进行详细的学习讲解,这次就全当是一次热身吧!

测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202009/source/11.学习PHP中的国际化功能来查看货币及日期信息.php

The above is the detailed content of Learn the internationalization function in PHP to view currency and date information. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:硬核项目经理. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.