[함수] array_iconv - 1~n차원 배열의 key, value 문자 인코딩 변환 함수
PHP를 이용해서 개발하다보면 1차원 이상의 배열 key랑 value 모든 값에 대해 인코딩을 변환해줘야할 때가 있습니다. 그 때마다 foreach로 일일이 iconv 함수를 수행하는 것이 번거로운 것 같아 아래와 같이 함수를 만들어보았습니다.
function array_iconv( $Current, $Next, $Array , $AutoDetect = true ) {
$new_array = array();
$Current = strtoupper($Current);
$Next = strtoupper($Next);
$encode = array($Current,str_replace('//IGNORE','',$Next));
foreach($Array as $key => $val) {
if(is_string($key) && (($AutoDetect == true && mb_detect_encoding($key,$encode) == $Current) || $AutoDetect == false)) {
$key = iconv($Current, $Next, $key);
}
if(is_string($val) && (($AutoDetect == true && mb_detect_encoding($val,$encode) == $Current) || $AutoDetect == false)) {
$val = iconv($Current, $Next, $val);
}
if(is_array($val)) $val = array_iconv( $Current, $Next, $val, $AutoDetect);
$new_array[$key] = $val;
}
return $new_array;
}
사용법은 iconv와 동일합니다. 대신 3번째 인자가 string이 아니라 array를 넘겨주시면 됩니다.
iconv ignore 성질(글자 짤림 방지)을 이용할 수 있도록 구현해두었습니다. // str_replace 부분 참조
4번째 값은 true, false로 나눠집니다. EUC-KR 문자를 UTF-8로 바꾼다고 할때, 해당 문자가 이미 UTF-8인 경우에는 iconv가 실행되지 않도록 하기 위해서는 true(기본값)으로 해주셔야합니다.
무조건 인코딩이 실행되게 하고 싶으시다면 false를 넣어주시면 됩니다.
<?php
$a = array('테스트' => '합니다', 'PHP는' => '쉬워요');
$b = array_iconv("EUC-KR","UTF-8",$a,true);
print_r($b);
?>
// UTF-8 형태로 문자가 출력 될 것입니다.
위의 array_iconv 함수랑 string의 iconv를 동시에 사용하고 싶으시면
function iconv2( $Current, $Next, $Array , $AutoDetect = true ) {
if(!is_array($Array)) return iconv($Current,$Next,$Array); // 이 한줄만 추가되었습니다.
$new_array = array();
$Current = strtoupper($Current);
$Next = strtoupper($Next);
$encode = array($Current,str_replace('//IGNORE','',$Next));
foreach($Array as $key => $val) {
if(is_string($key) && (($AutoDetect == true && mb_detect_encoding($key,$encode) == $Current) || $AutoDetect == false)) {
$key = iconv($Current, $Next, $key);
}
if(is_string($val) && (($AutoDetect == true && mb_detect_encoding($val,$encode) == $Current) || $AutoDetect == false)) {
$val = iconv($Current, $Next, $val);
}
if(is_array($val)) $val = iconv2( $Current, $Next, $val, $AutoDetect);
$new_array[$key] = $val;
}
return $new_array;
}
iconv2("EUC-KR","UTF-8",array('인코딩' => '성공'));
iconv2("EUC-KR","UTF-8","EUC-KR을 UTF-8로 인코딩해봅니다");
이렇게 사용하실 수 있겠습니다.. ^^
- phpschool
'개발-PHP' 카테고리의 다른 글
[함수] XenoImage class makeCropThumbnail (0) | 2016.03.30 |
---|---|
[함수] 왕 초보가 올리는 파일 업로드 방법 (0) | 2016.03.30 |
[함수] 제로보드 댓글 스팸 동시 전체삭제 (0) | 2016.03.30 |
[함수] [함수 셀렉트박스] 만들기 처음으로 올림 ㅋ (0) | 2016.03.30 |
[함수] set_error_handler 함수 한계 극복하기 (0) | 2016.03.30 |