Advertisement
krot

csv

Mar 14th, 2019
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.86 KB | None | 0 0
  1. <?php
  2. namespace type;
  3. use Exception;
  4. class Csv{
  5.     private $hnd;
  6.     public $error=true;
  7.     function __construct($filePath){
  8.         $this->hnd = fopen($filePath, "r");
  9.         if($this->hnd===false){
  10.             $error=true;
  11.              throw new Exception('fopen');
  12.             return;
  13.         }
  14.          if(!flock($this->hnd,LOCK_SH)){
  15.              throw new Exception('flock');
  16.          }
  17.     }
  18.     function read(){
  19.         $ln=fgets($this->hnd,1024);
  20.         if(($ln===false)or(($ln===null)))return false;
  21.         $row=str_getcsv($ln,';');
  22.         if(sizeof($row)===1)$row=str_getcsv($ln,',');
  23.         array_walk_recursive($row,
  24.              function   (&$item, $key) {
  25.                  $c=mb_detect_encoding($item,array('UTF-8','Windows-1251'));
  26.                  if($c<>'UTF-8')$item = iconv(mb_detect_encoding($item,array('Windows-1251','UTF-8')),"UTF-8",$item);
  27.                     }
  28.             );
  29.         return $row;
  30.     }
  31.     function __destruct(){
  32.         flock($this->hnd,LOCK_UN);
  33.         fclose($this->hnd);
  34.     }
  35.    
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement