Create simple JSON data from PHP from mysql query

function was not tested, minor modification will be needed. For this in Java

Example output:
{
“status”:”200″,
“error_message”:””,
“item”:[
{“ID”:”18″, “Name”:”Item A”} ,
{“ID”:”19″, “Name”:”Item B”} ,
{“ID”:”20″, “Name”:”Item C”} ,
{“ID”:”21″, “Name”:”Item D”}
]
}

</pre>
function constructJson($query){
 $json_str = "";
 $row_count = 0;
 if($total=mysql_num_rows($query)){
 $json_str = constructJsonHead().constructJsonStatus(200,"")."[";
 $json_item = "";
 while($data=mysql_fetch_assoc($query)){
 $count = 0;
 if(count($data)>1)
 $json_item .= constructJsonHead();

foreach($data as $key => $value){
 if(count($data)>1)
 $json_item .= "\"$key\":\"$value\"";
 else
 $json_item .= "\"$value\"";

$count++;
 if($count < count($data)) $json_item .= ",\n"; } $row_count++; if(count($data) > 1)
 $json_item .= constructJsonTail()."\n";

if($row_count < $total)
 $json_item .= ",\n";

}
 }else{
 $json_str .= constructJsonHead().constructJsonStatus(201,"No Item")."[]".constructJsonTail();
 }
 return $json_str.$json_item."]".constructJsonTail();
}

function constructJsonStatus($response_code,$msg){
 return "\"status\":\"$response_code\",\"error_message\":\"$msg\",\"item\":";
}

function constructJsonHead(){ return "{";}
function constructJsonTail(){ return "}";}
<pre>
Advertisements

Posted on February 27, 2014, in Uncategorized and tagged , , . Bookmark the permalink. 1 Comment.

  1. Thanks buddy. I was stuck on this since a long time. I dint know how to parse xml data.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: