PHP code example of chinayin / ip2region-core

1. Go to this page and download the library: Download chinayin/ip2region-core library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chinayin / ip2region-core example snippets


use ip2region\XdbSearcher;

$ip = '1.2.3.4';
$xdb = './ip2region.xdb';
try {
    $region = XdbSearcher::newWithFileOnly($xdb)->search($ip);
    var_dump($region);
} catch (\Exception $e) {
    var_dump($e->getMessage());
}

use ip2region\XdbSearcher;

$ip = '1.2.3.4';
$xdb = './ip2region.xdb';
try {
    // 1、加载 VectorIndex 缓存,把下述的 vIndex 变量缓存到内存里面。
    $vIndex = XdbSearcher::loadVectorFromFile($xdb);
    if (null === $vIndex) {
throw new \RuntimeException("failed to load vector index from '$xdb'.");
    }
    // 2、使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
    $searcher = XdbSearcher::newWithVectorIndex($xdb, $vIndex);
    // 3、查询
    $region = $searcher->search($ip);
    var_dump($region);
} catch (\Exception $e) {
    var_dump($e->getMessage());
}

use ip2region\XdbSearcher;

$ip = '1.2.3.4';
$xdb = './ip2region.xdb';
try {
    // 1、加载整个 xdb 到内存。
    $cBuff = XdbSearcher::loadContentFromFile($xdb);
    if (null === $cBuff) {
        throw new \RuntimeException("failed to load content buffer from '$xdb'");
    }
    // 2、使用全局的 cBuff 创建带完全基于内存的查询对象。
    $searcher = XdbSearcher::newWithBuffer($cBuff);
    // 3、查询
    $region = $searcher->search($ip);
    var_dump($region);
} catch (\Exception $e) {
    var_dump($e->getMessage());
}