首页 > 解决方案 > libphonenumber PHP 国家/地区

问题描述

我正在使用这个库:https ://github.com/davideme/libphonenumber-for-PHP 。这是演示代码:

<?php
use com\google\i18n\phonenumbers\PhoneNumberUtil;
use com\google\i18n\phonenumbers\PhoneNumberFormat;
use com\google\i18n\phonenumbers\NumberParseException;

require 'PhoneNumberUtil.php';

$swissNumberStr = "1212-894-3000";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
    $swissNumberProto = $phoneUtil->parseAndKeepRawInput($swissNumberStr, "US");

    echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::E164) . PHP_EOL;


echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL) . PHP_EOL;
echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::NATIONAL) . PHP_EOL;
echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::E164) . PHP_EOL;

echo $phoneUtil->formatOutOfCountryCallingNumber($swissNumberProto, "US") . PHP_EOL;    
} catch (NumberParseException $e) {
    echo $e;
}

这是我的输出:

Error type: 0. Missing or invalid default region.

巴基斯坦和其他国家/地区的代码有效,但"US", "Canada","UK"等无效。

标签: phplibphonenumber

解决方案


我相信代码中存在错误。我已经修好了。该错误位于PhoneNumberUtil.php 中。函数名称

private function init($filePrefix) {

在第 231 行正在搜索一个名为 REGION_CODE_FOR_NON_GEO_ENTITY 的键,它等于在线定义的“001”119。由于数组中没有匹配“001”的键,它会取消设置“US”的第 0 个元素。我已经修复了这个错误,我将在 GitHub 上向开发人员报告。新功能如下。

private function init($filePrefix) {
    $this->currentFilePrefix = dirname(__FILE__) . '/data/' . $filePrefix;
    foreach ($this->countryCallingCodeToRegionCodeMap as $regionCodes) {
        $this->supportedRegions = array_merge($this->supportedRegions, $regionCodes);
    }
    $nongeoentity=array_search(self::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
    if($nongeoentity)
    unset($this->supportedRegions[array_search(self::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions)]);
    $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[self::NANPA_COUNTRY_CODE];
}

推荐阅读