CURL를 활용하여 POST방식으로 JSON데이터 주고 받기
페이지 정보
작성자 서방님 댓글 0건 조회 75회 작성일 20-04-23 13:13본문
//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; ?>
댓글목록
등록된 댓글이 없습니다.