2016. 2. 18. 17:22

conf 파일 리더

ActionScript 쪽에서 PropertiesConfigurationFactory 라는 클래스를 통해 아래와 같은 형식의 파일 내용을 읽어 들이는데 PHP에서도 읽을 필요가 있어서 간단히 제작함


KEY = 내용내용

KEY2 = 내용내용

#KEY3 = 주석

//KEY4 = 주석


<?php class ConfReader { /** * @var array */ private $_data; /** * @param $key * @return null|string */ public function get($key) { if(isset($this->_data[$key])) return $this->_data[$key]; else return null; } /** * @return array */ public function getAll() { return $this->_data; } /** * @param $filename string * @return bool */ public function load($filename) { if(!file_exists($filename)) return false; $fp = fopen($filename, 'r'); while(!feof($fp)) { $buf = trim(fgets($fp, 1024)); if(empty($buf) || $buf[0] == '#' || ($buf[0] == '/' && $buf[1] == '/')) continue; $tmp = explode('=', $buf); $cnt = count($tmp); if($cnt < 2) continue; elseif($cnt == 2) { $key = trim($tmp[0]); $value = trim($tmp[1]); if(empty($key)) continue; $this->_data[$key] = $value; } else { $key = trim($tmp[0]); $value = ""; for($i=1;$i<$cnt;++$i) { if($i == 1) $value .= $tmp[$i]; else $value .= "=".$tmp[$i]; } if($value) $this->_data[$key] = trim($value); } } fclose($fp); return true; } }