개발자의 끄적끄적

[php] json_encode content-type json 설정 방법 및 예제 본문

개발/php

[php] json_encode content-type json 설정 방법 및 예제

효벨 2021. 3. 8. 02:00
728x90
반응형

[php] json_encode content-type json 설정 방법 및 예제

 

 

php 에서

 

json_encode 를 사용하여

 

api 와 같은 결과를 반환할때,

 

아래와 같이 그냥 json_encode 를 출력하면,

 

echo json_encode($data);

 

결과를 받는 측에서는,

 

json string 형태로 보이지만, header 에는 content-type 이 html 형태로 인식하게 됩니다.

 

이것을 json 형태로 인식하게 하고 싶을때는

 

아래 header 내용을 세팅하여 전송하면 됩니다.

header('Content-type: application/json');

 

 

우선 아래와 같은 $data 라는 배열이 있다고 가정하고,

$data = array();
$data["a"] = "aa";

 

그 배열을 

 

json 형태로 전송하고 싶을때는

 

아래와 같이 header의 content-type 를 세팅하여 

 

json_encode 를 출력하면 됩니다!

header('Content-type: application/json');
echo json_encode($data);

 

참고들 하세요!

반응형
Comments