배열 출력
php에서 JSON 배열을 출력하는 방법은 연관배열을 json_encode 함수의 파라메터로 전달하면 됩니다.
<?php
header('Content-Type: application/json');
$member1 = array("name" => "서태지", "height" => "173cm", "weight" => "55kg");
$member2 = array("name" => "양현석", "height" => "180cm", "weight" => "70kg");
$member3 = array("name" => "이주노", "height" => "172cm", "weight" => "53kg");
// 3명의 정보를 memberData변수에 저장
$memberData = array($member1, $member2, $member3);
// 3명의 데이터가 JSON Array 문자열로 변환됨
$output = json_encode($memberData);
// 출력
echo urldecode($output);
?>
코드를 실행한 출력 결과는 다음과 같습니다.
[
{
"name": "서태지",
"height": "173cm",
"weight": "55kg"
},
{
"name": "양현석",
"height": "180cm",
"weight": "70kg"
},
{
"name": "이주노",
"height": "172cm",
"weight": "53kg"
}
]
여기서 한가지! JSON은 JavaScript Object Notation의 약자입니다. 번역하면 javascript 객체 표기법 정도인데 뜻 그대로 출력 형식으로 javascript 문법을 사용합니다. javascript 문법을 사용한다고 해서 javascript에서만 사용 가능한것이 아니라 표기법만 사용하는 것이므로 혼동하지 말아 주세요.
자세한 javascript 배열 정보는 http://www.w3schools.com/js/js_arrays.asp를 참고하세요.
참고로 phpcode에서 사용된 header('Content-Type: application/json')은 데이터가 JSON이라는 것을 명시합니다.
객체를 이용한 배열 + 데이터 출력
이번에는 JSON 배열과 함께 다른 값들도 함께 전달하는 코드 입니다.
<?php
// 그룹에 대한 정보를 저장
header('Content-Type: application/json');
$groupData = array();
$groupData["groupName"] = "서태지와 아이들";
$groupData["debutYear"] = "1992";
$groupData["memberCount"] = "3";
// 첫 번째 코드와 동일
$member1 = array("name" => "서태지", "height" => "173cm", "weight" => "55kg");
$member2 = array("name" => "양현석", "height" => "180cm", "weight" => "70kg");
$member3 = array("name" => "이주노", "height" => "172cm", "weight" => "53kg");
$memberData = array($member1, $member2, $member3);
// JSON Array를 연관 배열로 저장 키이름은 memberData
$groupData["memberData"] = $memberData;
// JSON Array가 포함된 Object를 문자열로 변환
$output = json_encode($groupData);
// 출력
echo urldecode($output);
?>
출력 결과는 다음과 같습니다.
{
"groupName": "서태지와 아이들",
"debutYear": "1992",
"memberCount": "3",
"memberData": [
{
"name": "서태지",
"height": "173cm",
"weight": "55kg"
},
{
"name": "양현석",
"height": "180cm",
"weight": "70kg"
},
{
"name": "이주노",
"height": "172cm",
"weight": "53kg"
}
]
}
출력된 형식은 javascript의 object 형식으로 필요한 데이터가 속성으로 표시되고 배열 역시 하나의 속성이 됩니다.
자세한 javascript의 object 관련 정보는 http://www.w3schools.com/js/js_objects.asp 링크를 참고하세요.
활용
form
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 합쳐지고 최소화된 최신 CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- 부가적인 테마 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<!-- 합쳐지고 최소화된 최신 자바스크립트 -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-xs-3 col-sm-3"></div>
<div class="col-xs-8 col-sm-8">
<h1> </h1>
<form method="post" action="test.php" name="form1">
<table class="table">
<tr>
<th>To</th>
<td><input type="text" name="alim_to" value="821012345678" class="form-control" ></td>
</tr>
<tr>
<th>Text</th>
<td><textarea name="alim_text" class="form-control" rows="15" cols="20">홍길동님, 안녕하세요. 슈어엠주식회사입니다.</textarea></td>
</tr>
<tr>
<th>From</th>
<td><input type="text" name="alim_from" value="07076380579" class="form-control" ></td>
</tr>
<tr>
<th>code</th>
<td><input type="text" name="alim_template_code" value="completed_001" class="form-control"></td>
</tr>
<tr>
<th>Time</th>
<td><input type="text" name="alim_reserved_time" value="209912310000" class="form-control" ></td>
</tr>
<tr>
<th>Send</th>
<td><input type="text" name="alim_re_send" value="R" class="form-control" ></td>
</tr>
<tr>
<th>Text</th>
<td><input type="text" name="alim_re_text" value="대체 메시지입니다." class="form-control" ></td>
</tr>
<tr>
<td colspan="2" class="text-center"><input type="submit" value="전송" class="btn btn-success" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
test.php
<?
header("Content-Type: text/html; charset=UTF-8");
//header('Content-Type: application/json');
$usercode="1111";
$deptcode="2222";
$yellowid_key="3333";
//폼에 전송된 데이터를 받아 옵니다.
$alim_to=$_POST["alim_to"];
$alim_text=$_POST["alim_text"];
$alim_from=$_POST["alim_from"];
$alim_template_code=$_POST["alim_template_code"];
$alim_reserved_time=$_POST["alim_reserved_time"];
$alim_re_send=$_POST["alim_re_send"];
$alim_re_text=$_POST["alim_re_text"];
/*
{
"usercode" : "1111",
"deptcode" : "2222",
"yellowid_key" : "3333",
"messages" :
[
{
"to" : "821012345678",
"text" : "홍길동님, 안녕하세요. 슈어엠주식회사입니다.",
"from" : "07076380579",
"template_code" : "completed_001",
"reserved_time" : "209912310000",
"re_send" : "R",
"re_text" : "대체 메시지입니다."
}
]
}
*
*/
// json Jsongroup 를 만듭니다.
$groupData=array();
$groupData["usercode"]=$usercode;
$groupData["deptcode"]=$deptcode;
$groupData["yellowid_key"]=$yellowid_key;
$messages=array(
"to" => $alim_to,
"text" => $alim_text,
"from" => $alim_from,
"template_code" =>$alim_template_code,
"reserved_time" => $alim_reserved_time,
"re_send" => $alim_re_send,
"re_text" => $alim_re_text
);
//messages 객체가 배열에 [] 안에 포함되어 있으므로 $messagesData 를 만듭니다.
$messagesData =array($messages);
$groupData["messages"] = $messagesData;
// JSON Array가 포함된 Object를 문자열로 변환
// json_encode는 PHP의 데이터를 JSON 형식으로 전환해주는 PHP의 내장함수다.
$output = json_encode($groupData);
$ch = curl_init('~~');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=UTF-8',
'Content-Length: ' . strlen($output))
);
$result = curl_exec($ch);
// 출력
//전송된 Json 데이터 확인
//echo urldecode($output);
// https://api.surem.com/alimtalk/v1/json 전송 후 받은 메시지
var_dump($result);
?>













댓글 ( 4)
댓글 남기기