PHP 한글 깨짐 해결 방법

프리터코더·2025년 5월 25일
0

php 문제 해결

목록 보기
16/79

기본 설정

1. PHP 파일 인코딩 설정

header('Content-Type: text/html; charset=UTF-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

2. HTML 메타 태그

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>

3. 데이터베이스 설정

// MySQL 연결 설정
$pdo = new PDO(
    "mysql:host=localhost;dbname=mydb;charset=utf8mb4",
    $username,
    $password
);

// 쿼리 실행 전 설정
$pdo->query("SET NAMES utf8mb4");

파일 처리

1. 파일 읽기/쓰기

// 파일 읽기
$content = file_get_contents('file.txt');
$content = mb_convert_encoding($content, 'UTF-8', 'auto');

// 파일 쓰기
file_put_contents('file.txt', $content, LOCK_EX);

2. CSV 파일 처리

// CSV 파일 읽기
setlocale(LC_ALL, 'ko_KR.UTF-8');
$handle = fopen('data.csv', 'r');
while (($data = fgetcsv($handle)) !== FALSE) {
    $data = array_map('utf8_encode', $data);
}

폼 데이터 처리

// POST 데이터 처리
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$name = mb_convert_encoding($name, 'UTF-8', 'auto');

URL 처리

// URL 인코딩
$url = urlencode($koreanText);

// URL 디코딩
$text = urldecode($encodedUrl);

유틸리티 함수

class EncodingUtils {
    public static function toUTF8($text) {
        return mb_convert_encoding($text, 'UTF-8', mb_detect_encoding($text));
    }
    
    public static function convertArray($array) {
        array_walk_recursive($array, function(&$item) {
            $item = self::toUTF8($item);
        });
        return $array;
    }
}

실제 구현 예시

// 설정
header('Content-Type: text/html; charset=UTF-8');
mb_internal_encoding('UTF-8');

// 데이터베이스 쿼리
$stmt = $pdo->prepare("SELECT name FROM users WHERE id = ?");
$stmt->execute([$id]);
$name = $stmt->fetchColumn();

// 출력
echo "<div>사용자 이름: {$name}</div>";
profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글