Transfer data from PHP to Android (JSON) – Part 1

You may reach a point where you need to transfer data from a server (web-service) to a an android client. although, there are many ways to achieve that goal, one of the simplest is using JSON. JSON is better then XML in terms of small bandwidth footprint. it has a lot of libraries for every available platform, so it makes the best solution for server-client communication.

If you want to read more about JSON string structure you should follow here.


prerequisites:

  • PHP Server with JSON (PHP 5.2 have a native support for JSON)

 

Creating SERVER Side (PHP):

The concept is very simple. a php file returning an encoded JSON string to be read from android device (or anywhere else)

This are two samples of a PHP file. the first (Array.php) is simple, and return a static array. the other (SQL.php), returns data from SQL.

 

Array.php:

1
2
3
4
5
6
7
<?php
   include 'lib/JSON.php';
   /* create data array */
   $posts = array("fname" => "foo", "lname" => "bar");
   /* encode the JSON post from the array */
   encodearray($posts);
?>
<?php
   include 'lib/JSON.php';
   /* create data array */
   $posts = array("fname" => "foo", "lname" => "bar");
   /* encode the JSON post from the array */
   encodearray($posts);
?>

Which returns to browser:

1
{"posts":{"fname":"foo","lname":"bar"}}

SQL.php

1
2
3
4
5
6
<?php
   include 'lib/JSON.php';
   /* grab the posts from the db */
   $query = "SELECT * FROM users ORDER BY date";
   encodequery($query);
?>
<?php
   include 'lib/JSON.php';
   /* grab the posts from the db */
   $query = "SELECT * FROM users ORDER BY date";
   encodequery($query);
?>

Which returns to browser:

1
{"posts":[{"post":{"date":"2003-03-03","name":"user","age":"31","color":"red"}}]}

lib/JSON.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
 
/* disable cache in browser */
 
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
 
/* encode an sql query */
 
function encodequery($query) {
   /* sql connnection link - fill your details*/
   $link = mysql_connect('server','username','password')
   or die('connection to the DB failed.');
   mysql_select_db('database',$link) or die('Cannot find DB.');
   $result = mysql_query($query,$link) or die('Error in query: '.$query);
   /* create one master array of the records */
   $posts = array();
   if(mysql_num_rows($result)) {
      while($post = mysql_fetch_assoc($result)) {
         $posts[] = array('post'=>$post);
      }
   }
   encodearray($posts);
}
 
/* Encode array to JSON string */
function encodearray($posts) {
   header('Content-type: application/json');
   echo json_encode(array('posts'=>$posts));
}
 
?>
<?php

/* disable cache in browser */

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

/* encode an sql query */

function encodequery($query) {
   /* sql connnection link - fill your details*/
   $link = mysql_connect('server','username','password')
   or die('connection to the DB failed.');
   mysql_select_db('database',$link) or die('Cannot find DB.');
   $result = mysql_query($query,$link) or die('Error in query: '.$query);
   /* create one master array of the records */
   $posts = array();
   if(mysql_num_rows($result)) {
      while($post = mysql_fetch_assoc($result)) {
         $posts[] = array('post'=>$post);
      }
   }
   encodearray($posts);
}

/* Encode array to JSON string */
function encodearray($posts) {
   header('Content-type: application/json');
   echo json_encode(array('posts'=>$posts));
}

?>

* The file JSON.php is an include file used by both SQL.php & Array.php.


in the next article you will create the client side ->

3 thoughts on “Transfer data from PHP to Android (JSON) – Part 1

  1. XerVon

    Трeвoжная кнoпка или тревожная кнопка gsm служит для моментального вызова мобильной группы с случае опасной ситуации.

    Является неотъемлемой частью технической охpaны для банков, ювелирных и оружейных магазинов, продовольственных магазинов и магазинов непродовольственных товаров, учебных учреждений, ресторанов и даже частных дoмoв.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.