곰시기's

[PHP] - 간단한 iconv 함수 본문

Web Development/PHP

[PHP] - 간단한 iconv 함수

곰시기 2021. 2. 16. 15:51
function fncIconv( $obj, $target = "all", $endEnc = "EUC-KR" ) {
  /*
   * $obj      : 사용자로 부터 받아오는 변수
   * $target   : $obj가 배열일 경우 문자 셋 변경 대상 all / key / val 
   * $endEnc   : 변경할 문자 셋
   * $type_obj : $obj의 type 확인
   * $key      : 배열의 key
   * $val      : 배열의 value
   * $type_arr : $val의 type 확인용
   * $encType  : 변경 대상의 문자 셋
   * $rtn      : 반환 값
   */

  $type_obj = strtoupper( gettype( $obj ) );

  if( $type_obj == "ARRAY" || $type_obj == "OBJECT" ) {

    if( $type_obj == "OBJECT" ) {
      $obj = ( array )$obj;
    }

    foreach( $obj as $key => $val ) {
      $type_arr = strtoupper( gettype( $val ) );
      
      if( $type_arr == "ARRAY" ) { # 배열 $arr의 값( $val )이 배열인지 아닌지 확인
        fncIconv( $val, $target, $endEnc ); # 배열이면 재귀함수
      }

      $endEnc  = strtoupper( $endEnc ); # 사용자가 변환하고자하는 문자 셋

      // echo "{$encType} => {$endEnc} | target : {$target} | before [ key:{$key} | val:{$val} ]<br />\n";
      if( $target == "key" || $target == "all" ) {
        $encType = strtoupper( mb_detect_encoding( $key, "auto" ) ); # $key의 문자 셋 확인 / 대문자로 치환

        if( $encType != $endEnc ) { # 문자 셋이 서로 다를때 인코딩 진행
          $key = iconv( $encType, $endEnc, $key );
        }
      }

      if( ( $target == "val" || $target == "all" ) && $type_arr != "ARRAY" ) {
        $encType = strtoupper( mb_detect_encoding( $val, "auto" ) ); # $val의 문자 셋 확인 / 대문자로 치환

        if( $encType != $endEnc ) { # 문자 셋이 서로 다를때 인코딩 진행
          $val = iconv( $encType, $endEnc, $val );
        }
      }
      // echo "{$encType} => {$endEnc} | target : {$target} | after  [ key:{$key} | val:{$val} ]<br />\n";
      // echo "\n\n";

      $rtn[$key] = $val;
    }
  } else if( $type_obj == "INTEGER" || $type_obj == "DOUBLE" ) {
    $rtn = $obj;
  } else if( $type_obj == "STRING" ) {
    $encType = strtoupper( mb_detect_encoding( $obj, "auto" ) );
    $rtn = iconv( $encType, $endEnc, $obj );
  }else if( $type_obj == "NULL" || $type_obj == "UNKNOWN TYPE" ) {
    $rtn = "";
  } else if( $type_obj == "BOOLEAN" ) {
    $rtn = $obj;
  }else {
    $rtn = false;
  }
  return $rtn;
}

'Web Development > PHP' 카테고리의 다른 글

[PHP] - Select Box  (0) 2021.02.16
[PHP] - JsonEncoder 함수  (0) 2021.02.16
[PHP] - 원격지 파일 다운로드  (0) 2021.02.16
[PHP] - 문자열 앞까지 자르기  (0) 2021.02.16
[PHP] - mysql_free_result  (0) 2021.01.20
Comments