Advertisement
Guest User

Untitled

a guest
Jul 11th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.58 KB | None | 0 0
  1.     function ip_csv2dat($input_file, $output_file) {
  2.  
  3.         $lines = file($input_file);
  4.         $fh = fopen($output_file, 'wb+');
  5.         fwrite($fh, 'TKdb');
  6.         fwrite($fh, pack('l', 0));
  7.         $min = NULL;
  8.         $countries = array();
  9.         $cnt = 0;
  10.         $topidx = array();
  11.         $minip = 0;
  12.         $maxip = 0;
  13.         foreach ($lines as $line) {
  14.             $cnt++;
  15.             $line = str_replace('"', '', $line);
  16.             list($start, $end, $two, , ) = explode(',', $line, 4);
  17.             $start = "$start" + 0;
  18.             $end = "$end" + 0;
  19.             if (!in_array($two, $countries)) {
  20.                 $countries[] = $two;
  21.             }
  22.             $countryidx = array_search($two, $countries);
  23.             fwrite($fh, pack('VVv', $start, $end, $countryidx));
  24.             list($aclassStart, , , ) = explode('.', long2ip($start));
  25.             list($aclassEnd, , , ) = explode('.', long2ip($end));
  26.             for ($i = $aclassStart; $i <= $aclassEnd; $i++) {
  27.                 if (!isset($topidx[$i])) {
  28.                     $topidx[$i] = $cnt;
  29.                 }
  30.             }
  31.             if (is_null($min)) {
  32.                 $min = $start;
  33.                 $minip = $aclassStart;
  34.             }
  35.             $max = $end;
  36.             $maxip = $aclassEnd;
  37.         }
  38.         $idx = ftell($fh);
  39.         fwrite($fh, pack('VVVCv', $cnt, $min, $max, strlen(pack('VVv', 'P', 'H', 'P')), count($countries)));
  40.         foreach ($countries as $country) {
  41.             fwrite($fh, $country);
  42.         }
  43.         fwrite($fh, pack('CC', $minip, $maxip));
  44.         $lastpos = 0;
  45.         $pos = 0;
  46.         for ($i = $minip; $i <= $maxip; $i++) {
  47.             if (isset($topidx[$i])) {
  48.                 $pos = $topidx[$i];
  49.                 $lastpos = $pos;
  50.             } else {
  51.                 $pos = -$lastpos;
  52.             }
  53.             fwrite($fh, pack('i', $pos));
  54.         }
  55.         fseek($fh, 4);
  56.         fwrite($fh, pack('l', $idx));
  57.         fclose($fh);
  58.         return array(0 => $cnt, 1 => count($countries));
  59.  
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement