안녕하세요

 

오랫만에 PHP 관련 글을 올리네요.

 

이번 글은 API 연동을 하다보니 JSON 데이터를 POST방식으로 주고 받는 경우가 발생하여

내용을 정리해보았습니다. 

 

많은 도움이 되면 좋을 것 같습니다.^^

 

//POST로 전송할 JSON 데이터 샘플
{
    "user" : { "id" : "xxxxxxx"},
    "log":[
              {
                  "id":"1",
                  "log_val": "43"

              },
              {
                  "id":"2",
                  "log_val": "44"
              }
	  		]

}

//JSON 결과 데이터 샘플
{
    "result" : "200",
    "msg":[
            {
                "id":"1",
                "msg_val": "43_OK"

            },
            {
                "id":"2",
                "msg_val": "44_OK"
            }
          ]

}


<?php
//---------------------CURL를 활용하여 JSON데이터를 POST방식으로 요청하여 JSON데이터로 받기--------------------

//요청 서버 URL 셋팅
$url = "요청할 서버 URL";

//추가할 헤더값이 있을시 추가하면 됨
$headers = array(
		"content-type: application/json",
		"accept-encoding: gzip"
);

//POST방식으로 보낼 JSON데이터 생성
$arr_user = array();
$arr_log = array();
$arr_post = array();

$arr_user["id"] = "xxxxxxx";

$arr_post["user"] = $arr_user;

$arr_log[0]["id"] = "1";
$arr_log[0]["log_val"] = "43";
$arr_log[1]["id"] = "2";
$arr_log[1]["log_val"] = "44";

$arr_post["log"] = $arr_log;

//배열을 JSON데이터로 생성
$post_data = json_encode($arr_post);

//CURL함수 사용
$ch=curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
//header값 셋팅(없을시 삭제해도 무방함)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//POST방식
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
//POST방식으로 넘길 데이터(JSON데이터)
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

$response = curl_exec($ch);

if(curl_error($ch)){
    $curl_data = null;
} else {
    $curl_data = $response;
}

curl_close($ch);

//받은 JSON데이터를 배열로 만듬
$json_data = json_decode($curl_data,true);
//배열 제어
if($json_data["result"] == "200"){
	$cnt = 0;
	foreach($json_data["msg"] as $msg_data){
		foreach($msg_data as $msgval_data){
			//msg_val값만 출력합니다.
			echo $msgval_data[$cnt]["msg_val"];
			$cnt++;
		}
	}
}

exit;
?>

 

 

러닝 PHP : PHP 입문에서 프레임워크를 활용한 실전 프로그래밍까지(PHP 7 기반)

COUPANG

www.coupang.com

 

+ Recent posts