Using PHP on server side to generate JSON

Recently, I publish one application into the Android Market that tries to predict when Spain will default. The application uses the data provided by my colleague Juan Carlos Barba from his server. There are basically a set of levels pointing out the seriousness of the Spanish level of CDS and Spread of the debt. The model establishes 5 different levels of alert (or how he called them, DefCon). My implementation customized the data to visualize into the Android Platform.

Firstly, I needed to access his database into the server, which was a slow task due to the nature of the server (a personal computer with a normal DSL connection). My idea was to rely this task into something that could avoid overloading the server, and then I thought about everything that happens now with all the client / server application. Why not using a PHP file to generate JSON with the information I needed?

Since I do not have access to Juan Carlos’ server, I decided to do it on my own server. I created some PHP files that query the server, and give me the information in JSON format


Now the data has to be requested and handled from the Android side:

private void initPHP() {
		//http post
		 String result = "";
		  InputStream is = null ;
			 DefaultHttpClient httpclient = new DefaultHttpClient();
		         HttpPost httppost = new HttpPost("");
		         HttpResponse response = httpclient.execute(httppost);
		         HttpEntity entity = response.getEntity();
		         is = entity.getContent();
		 } catch(Exception e) {
		         Log.e("log_tag", "Error in http connection "+e.toString());
		 //convert response to string
		         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		         StringBuilder sb = new StringBuilder();
		         String line = null;
		         while ((line = reader.readLine()) != null) {
		                 sb.append(line + "\n");
		 }catch(Exception e){
		         Log.e("log_tag", "Error converting result "+e.toString());
		 //parse json data
		         JSONArray jArray = new JSONArray(result);
		         int lastDay = 0;
		         for(int i=0;i

The code can be improved to handle authentication, HTTPS, or do more complex work in general. In a project at work we used authentication based on a pair of generated keys, but a simple method based on a known keyword is enough.

Farver, a world color analyzer

Farver (the Danish word for “colors”) is a program that calculates the average color for a certain concept or word. It has been developed by Enrique López Mañas, although the original idea is from Douwe Osinga. He first did a desktop based application and some time ago I wanted to do a web based application (but he was faster and developed another web application). It uses the Google Image Search API and PHP as a primary language. The source code can be download from here. The application can be accessed here

Farver screenshot

Ahorcado en PHP y JavaScript

Profundizando en la tónica de compartir antiguos trabajos, cuelgo aquí uno de los trabajos que realicé recientemente: un juego del ahorcado alternativo que utiliza JavaScript si el navegador soporta scripting, y PHP en caso contrario.

El código fuente se puede descargar del siguiente enlace. Se divide en un fichero denominado modulo.php donde almaceno toda la información referente a la lógica del programa. Desde el fichero ahorcado.php se van reaalizando las llamadas.

En este ejemplo se pueden observar diferentes ejemplos del uso de PHP. Variables enviadas mediante sesión, inicialización de variables aleatorias, etc. Creo que se trata de un buen comienzo para sacar ideas que reutilizar en otras aplicaciones.

Si hay cualquier duda puedes ponerte en contacto mediante un comentario. Si te ha ayudado en algo, deja también un comentario (we all like to be flattered :-))

Al juego se puede acceder desde aquí