PHP에서 파일을 읽거나 웹 페이지 데이터를 가져올 때, 가장 간편하게 사용할 수 있는 함수가 file_get_contents() 입니다.
이 함수는 파일의 전체 내용을 문자열로 읽어오거나, 웹 URL에서 데이터를 가져올 때 유용하게 사용됩니다.
이 글에서는 PHP file_get_contents() 함수의 사용법, 다양한 활용 예제, fopen()과의 차이점, 유용한 팁과 주의사항을 체계적으로 정리하겠습니다.
1. file_get_contents() 함수란?
✅ 기본 문법
string file_get_contents(string $filename, bool $use_include_path = false, resource $context = null, int $offset = 0, int $max_length = null)
✅ 매개변수 설명
매개변수 설명
$filename | 읽어올 파일 경로나 URL |
$use_include_path (선택) | true 설정 시 include_path에서도 파일을 찾음 (기본값 false) |
$context (선택) | HTTP 요청 설정 (스트림 컨텍스트 사용 가능) |
$offset (선택) | 파일을 읽기 시작할 위치 (기본값 0) |
$max_length (선택) | 읽을 최대 바이트 수 (기본값: 파일 전체) |
✅ 반환값
- 파일의 내용을 문자열로 반환
- 파일을 읽을 수 없거나 오류 발생 시 false 반환
2. file_get_contents() 기본 예제
🔹 파일 전체 읽기
<?php
$content = file_get_contents("example.txt");
echo $content;
?>
➡ example.txt 파일의 모든 내용을 읽어와 출력합니다.
🔹 특정 위치부터 읽기 ($offset 사용)
<?php
$content = file_get_contents("example.txt", false, null, 10);
echo $content;
?>
➡ example.txt 파일의 10번째 바이트부터 끝까지 읽어옴.
🔹 특정 길이만큼 읽기 ($max_length 사용)
<?php
$content = file_get_contents("example.txt", false, null, 0, 100);
echo $content;
?>
➡ example.txt 파일의 처음부터 100바이트까지만 읽어옴.
3. 웹에서 데이터 가져오기 (file_get_contents() + URL)
🔹 외부 웹페이지 HTML 가져오기
<?php
$html = file_get_contents("https://www.example.com");
echo $html;
?>
➡ https://www.example.com의 HTML 소스를 가져와 출력합니다.
🔹 API 호출하여 JSON 데이터 가져오기
<?php
$json = file_get_contents("https://api.example.com/data");
$data = json_decode($json, true);
print_r($data);
?>
➡ API 응답을 JSON 형식으로 가져와 배열로 변환하여 활용할 수 있습니다.
🔹 HTTP 헤더 추가하여 요청 (stream_context_create() 활용)
<?php
$context = stream_context_create([
"http" => [
"header" => "User-Agent: PHP"
]
]);
$html = file_get_contents("https://www.example.com", false, $context);
echo $html;
?>
➡ User-Agent를 설정하여 요청할 수 있음.
4. file_get_contents() vs fopen() 차이점
함수 설명
file_get_contents() | 파일 전체를 문자열로 반환 |
fopen() + fread() | 파일을 한 줄씩 또는 일정 크기씩 읽을 수 있음 |
✅ 예제: fopen()과 비교
<?php
$handle = fopen("example.txt", "r");
$content = fread($handle, filesize("example.txt"));
fclose($handle);
echo $content;
?>
➡ fopen()을 사용하면 파일을 한 번에 읽거나, 줄 단위로 읽는 것이 가능하지만 file_get_contents()보다 코드가 길어짐.
5. file_get_contents()의 실용적인 활용 예제
🔹 1) 텍스트 파일 읽어오기
<?php
$file = "data.txt";
if (file_exists($file)) {
$content = file_get_contents($file);
echo $content;
} else {
echo "파일이 존재하지 않습니다.";
}
?>
➡ 파일이 존재하는 경우에만 내용을 읽도록 처리.
🔹 2) URL에서 JSON 데이터 가져와 파싱
<?php
$json = file_get_contents("https://api.example.com/users");
$users = json_decode($json, true);
foreach ($users as $user) {
echo "이름: " . $user["name"] . "<br>";
}
?>
➡ API에서 JSON 데이터를 가져와 파싱 후 출력.
🔹 3) PHP 파일을 읽어 문자열로 저장
<?php
$code = file_get_contents("script.php");
highlight_string($code);
?>
➡ PHP 코드를 읽어와 하이라이트 출력.
🔹 4) 웹페이지에서 특정 패턴의 데이터 추출
<?php
$html = file_get_contents("https://www.example.com");
if (preg_match('/<title>(.*?)<\/title>/', $html, $matches)) {
echo "페이지 제목: " . $matches[1];
}
?>
➡ 웹페이지의 <title> 태그 내용을 추출.
🔹 5) 파일 다운로드하여 저장
<?php
$imageUrl = "https://www.example.com/image.jpg";
$imageData = file_get_contents($imageUrl);
file_put_contents("downloaded.jpg", $imageData);
?>
➡ URL에서 파일을 다운로드하여 로컬에 저장.
6. file_get_contents() 사용 시 주의할 점
✅ 파일이 존재하는지 먼저 확인 (file_exists() 활용)
<?php
if (file_exists("example.txt")) {
$content = file_get_contents("example.txt");
} else {
echo "파일이 존재하지 않습니다.";
}
?>
➡ 파일이 없을 경우 오류 방지 가능.
✅ 파일이 크면 memory_limit 초과 가능 (fgets() 대안)
<?php
$handle = fopen("large.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>
➡ 대용량 파일을 처리할 때는 메모리 사용을 줄이기 위해 fgets() 사용 권장.
✅ URL 읽기 시 allow_url_fopen이 ON인지 확인
<?php
if (!ini_get("allow_url_fopen")) {
echo "URL을 읽을 수 없습니다.";
}
?>
➡ 서버 설정에서 allow_url_fopen = On이 되어 있어야 웹 데이터 가져오기 가능.
✅ SSL 인증서 검증 오류 방지 (verify_peer 설정)
<?php
$context = stream_context_create([
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
]);
$html = file_get_contents("https://self-signed.example.com", false, $context);
?>
➡ SSL 인증서 검증 문제로 file_get_contents()가 실패할 경우 해결 방법.
7. 결론
PHP의 file_get_contents() 함수는 파일 또는 URL에서 데이터를 쉽게 읽어오는 필수적인 함수입니다.
이를 활용하면 파일 읽기, 웹 데이터 크롤링, API 요청, 다운로드 등 다양한 작업을 수행할 수 있습니다.
📌 핵심 요약
✔️ file_get_contents()는 파일 또는 URL에서 데이터를 읽어와 문자열로 반환
✔️ API 요청 및 JSON 데이터 처리 가능
✔️ 대용량 파일 처리 시 fopen() + fgets()를 고려해야 함
✔️ allow_url_fopen 설정이 On이어야 URL에서 데이터 읽기 가능
이제 file_get_contents()를 활용하여 더욱 효율적인 PHP 개발을 해보세요! 🚀
💡 도움이 되셨다면 공유해주세요! 😊

'💻 자주 쓰는 PHP 함수' 카테고리의 다른 글
[PHP 함수] is_file() 함수로 파일 확인하기 (10) | 2025.03.25 |
---|---|
[PHP 함수] array_values() 함수로 배열 다루기 (14) | 2025.03.25 |
[PHP 함수] file_put_contents() 함수 완벽 가이드 (20) | 2025.03.24 |
[PHP 함수] array_key_exists() 함수 사용 가이드 (18) | 2025.03.23 |
[PHP 함수] array_keys() 함수 사용하기 (10) | 2025.03.23 |