PHP 에서 ini 파일을 읽기는 매우 쉽다.
parse_ini_file() 이라는 함수을 이용하면 된다.
parse_ini_file(경로,section=false) 요게 기본인데.
- ini 파일 예제
[GROUP] A = 1 B = 2
[GROUP2] C = 2 D =3 |
parse 할때 뒤 section 을 true 로 하면 읽었을때 section 까지 배열로 담아오고
false 일 경우 키랑 값만 불러온다.
- section False 일때
array (
[A] => 1,
[B] => 2,
[C] => 2,
[D] => 3
)
-section True 일때
array (
[GROUP] => Array (
[A] => 1,
[B] => 2
),
[GROUP2] => Array (
[C] => 2,
[D] => 3
)
)
파일을 읽은후 수정하고 다시 저장해야 할때가 있다.
그럴때는 뭐 어쩔수 없이 fwrite 를 이용해 그대로 다시 넣어 줄 수 밖에 없기에
함수로 만들어 사용!
// 호출
$this->__write_ini_file(배열, 파일경로, 섹션);
// ini 파일 write
private function __write_ini_file($assoc_arr, $path, $has_sections=FALSE) {
$content = "";
if ($has_sections) {
$i = 0;
foreach ($assoc_arr as $key=>$elem) {
if ($i > 0) {
$content .= "\n";
}
$content .= "[".$key."]\n";
foreach ($elem as $key2=>$elem2) {
if(is_array($elem2))
{
for($i=0;$i<count($elem2);$i++)
{
$content .= $key2."[] = \"".$elem2[$i]."\"\n";
}
} else if($elem2=="") {
$content .= $key2." = \n";
} else {
if (preg_match('/[^0-9]/i',$elem2)) {
$content .= $key2." = \"".$elem2."\"\n";
}else {
$content .= $key2." = ".$elem2."\n";
}
}
}
$i++;
}
}
else {
foreach ($assoc_arr as $key=>$elem) {
if(is_array($elem))
{
for($i=0;$i<count($elem);$i++)
{
$content .= $key."[] = \"".$elem[$i]."\"\n";
}
} else if($elem=="") {
$content .= $key." = \n";
} else {
if (preg_match('/[^0-9]/i',$elem)) {
$content .= $key." = \"".$elem."\"\n";
}else {
$content .= $key." = ".$elem."\n";
}
}
}
}
if (!$handle = fopen($path, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
유용할듯 시포요.
Comment Write
Comment List