'php'에 해당되는 글 2건

  1. 2012.04.26 PHP에서 json post 를 처리하는 방법.
  2. 2011.01.04 PHP 에서 UTF-8 관련 문제.

PHP에서 json post 를 처리하는 방법.

How to Handle JSon POST Request Using PHP


http://edwin.baculsoft.com/2011/12/how-to-handle-json-post-request-using-php/


On my last project, i need to create a php service using JSon to handle service requests from multiple clients. My PHP file would consume JSon string for its requests and produce JSon string as its responses.
Im not too familiar with PHP, but after sometime googling i’ve found a workaround. This is how i do it.

01<?php
02// JSon request format is :
03// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}
04 
05// read JSon input
06$data_back = json_decode(file_get_contents('php://input'));
07 
08// set json string to php variables
09$userName = $data_back->{"userName"};
10$password = $data_back->{"password"};
11$emailProvider = $data_back->{"emailProvider"};
12 
13// create json response
14$responses = array();
15for ($i = 0; $i < 10; $i++) {
16    $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
17}
18 
19// JSon response format is :
20// [{"name":"eeee","email":"eee@zzzzz.com"},
21// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
22 
23// set header as json
24header("Content-type: application/json");
25 
26// send response
27echo json_encode($responses);
28?>

This is the http header and body of request and response.

Hope it help others, have fun with JSon


지난글에서 C# 으로 post json 데이터를 날리는 경우에는

Content-Type 가 

application/x-www-form-urlencoded 

인 경우에는 $_POST[postData] 로 받아서 처리하면 되는데.


Content-Type 자체가 

application/json

인 경우에는 php 에서 위와 같이 처리한다.

PHP 에서 UTF-8 관련 문제.

기존의 euc-kr 등의 파일들을 UTF-8 로 컨버팅해서 작업을 할 경우에
UTF-8 로 컨버팅된 파일 앞에 BOM 이 붙게 된다.


뭐 unicode 에서는 BOM이 붙는게 정석이긴 한데. 
문제는 php 파일의 맨 앞에 3바이트의 BOM 이 있으면 그 3바이트를 그대로
출력을 한다.

일반 html 에서는 눈에 잘 안띄어서 잘 모를수도 있으나
xmlrpc 서버 같은 경우에도 맨 앞에 붙어서 출력이 되는 바람에
client 에서 제대로 parsing 을 못하는 아주 어이없는 상황이 
계속 발생한다.

php 파일들은 UTF-8 NO BOM 인코딩으로 새로 저장을 다 해주면 해결 할 수 있다.

'OLD POSTS' 카테고리의 다른 글

Fonts for ipad, iphone  (0) 2011.02.04
WPF의 datagrid 의 스타일 정의.  (0) 2011.01.07
Stencil Routed K-Buffer  (0) 2010.12.29
Tile Map Editor  (0) 2010.12.26
OpentTK/WPF integration  (0) 2010.12.22
prev 1 next