Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, October 30, 2012

android parse json response from php url

Create a PHP file to return JSON output from an array. Then create android activity and a java file to navigate to the URL and get the response from the PHP URL to implement into your page. Make sure to use your system IP instead of localhost or 127.0.0.1. Your code will be running on the emulator (a separate device from your machine) which will not identify the localhost. So you have to make sure to keep your IP in your URL. This will solve your "java.net.ConnectException: localhost/127.0.0.1:80 - Connection refused" issue in android. Also make sure to include the below line into your androidmanifest.xml file "
 <uses-permission android:name="android.permission.INTERNET" />  
" This will solve you the "java.net.SocketException: Permission denied" issue.
List.php
 <?php  
 $lst = array("1"=>"aa", "2"=>"bb", "3"=>"cc");  
 echo json_encode($lst);  
 ?>  
SampleJson.java
 package com.navigation.samplenavigation;  
 import java.io.IOException;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 import com.navigation.samplenavigation.R.id;  
 public class SampleNavigationActivity extends Activity {  
       // contacts JSONArray  
   JSONArray contacts = null;  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_sample_navigation);  
     final Button button = (Button) findViewById(id.submit);  
     button.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     // TODO Auto-generated method stub                                          
                     JSONObject json = null;  
                     try {                                
 json = JsonReader.readJsonFromUrl("http://10.91.28.56/php/jsonreturn/list.php");  
                     } catch (IOException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }  
                     System.out.println(json.toString());  
                     try {  
                          System.out.println(json.get("1"));  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }                      
                }  
           });  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.activity_sample_navigation, menu);  
     return true;  
   }    
 }  
JsonReader.java
 package com.navigation.samplenavigation;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import java.io.Reader;  
 import java.net.URL;  
 import java.nio.charset.Charset;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 public class JsonReader {  
  private static String readAll(Reader rd) throws IOException {        
   StringBuilder sb = new StringBuilder();  
   int cp;  
   while ((cp = rd.read()) != -1) {  
    sb.append((char) cp);  
   }  
   return sb.toString();  
  }  
  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {        
   InputStream is = new URL(url).openStream();  
   try {         
    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));     
    String jsonText = readAll(rd);     
    JSONObject json = new JSONObject(jsonText);  
    return json;  
   } finally {  
    is.close();  
   }  
  }   
 }  

Thursday, September 1, 2011

Javascript print_r dump function

print_r functionality of PHP in JavaScript. Here is the function called dump will give the result of objects and arrays. You can view JavaScript Objects and JavaScript arrays by calling dump function.



/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 */
function dump(arr, level) {
    var dumped_text = "";
    if (!level) level = 0;


    //The padding given at the beginning of the line.
    var level_padding = "";
    for (var j = 0; j < level + 1; j++) level_padding += "    ";


    if (typeof (arr) == 'object') { //Array/Hashes/Objects 
        for (var item in arr) {
            var value = arr[item];


            if (typeof (value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value, level + 1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
    }
    return dumped_text;
}

Thursday, February 10, 2011

PostgreSQL Dump Database

PostgreSQL Dump Database and Move Database from one server to another server.

for exporting the database to dump from localhost use the below query
pg_dump -h localhost -p 5432 -U madhavan Source_DB > db.Export.dump

for importing database into server
psql -h 192.168.1.7 -p 5432 -U postgres Source_DB < db.Export.dump

here
-h : Host to copy from
-p : Port
-U : Username of the database
after enter the query it will ask for password for the data base

Wednesday, February 2, 2011

Learn Map Server with PHP

Learn Map server

Map server is one of the biggest resource to represent data graphically.

To learn about Map server, here the link.

Thursday, January 27, 2011

Simple XML Chart Application For Any Application

Here is the simple Chart application. We can use any type of programming and in any platform. Here is the XML/SWF chart application.

Chart Application

Monday, December 20, 2010

Testing credit card numbers list

List of credit card numbers to test for web developers.

Here is the sample credit card numbers to test

List of Credit Card numbers

Tuesday, December 7, 2010

Learn Mysqli with PHP

Learn PHP - Mysqli


http://www.rvdavid.net/using-stored-procedures-mysqli-in-php-5/

Friday, December 3, 2010

PHP result set to multi select options

PHP Array result set into category wise multi select.


public function FormatEducationOnJobApplicants($Education, $SelectedEducation = '')
{
$EducationCategory = array();
$Select = '';
$OptGroup = '';
foreach($Education as $Row)
{
if(!in_array($Row['EducationCategory'], $EducationCategory))
{
if($OptGroup != '')
{
$Select .= "";
}
array_push($EducationCategory, $Row['EducationCategory']);
$Select .= "";
$OptGroup = $Row['EducationCategory'];
}
if(is_array($SelectedEducation))
{
$Select .= "";
}
else
{
$Select .= "";
}
}
if($OptGroup != '')
{
$Select .= "
";
}
return $Select;
}

Wednesday, November 10, 2010

PHP Object Buffering ob_start() and ob_flush()

PHP Object Buffering

bool ob_start ( [callback output_function])
bool ob_end_flush ( void )
bool ob_end_clean ( void )

There are two ways to start buffering output:
through a setting in php.ini to enable output
buffering for all scripts, or by using a function
call on a script-by-script basis. Surprisingly,
the latter is preferred - it makes your code
more portable, and also gives you greater flexibility.

To create a new output buffer and start
writing to it, call ob_start(). There are
two ways to end a buffer, which are ob_end_flush()
and ob_end_clean() - the former ends the buffer
and sends all data to output, and the latter ends
the buffer without sending it to output.
Every piece of text outputted while an output
buffer is open is placed into that buffer
as opposed to being sent to output.
Consider the following script:

ob_start();
print "Hello First!\n";
ob_end_flush();

ob_start();
print "Hello Second!\n";
ob_end_clean();

ob_start();
print "Hello Third!\n";
?>

ob_start();
print "Hello First!\n";
ob_end_flush();

ob_start();
print "Hello Second!\n";
ob_end_clean();

ob_start();
print "Hello Third!\n";
?>



Reusing buffers



void ob_flush ( void )
void ob_clean ( void )

The functions ob_end_flush() and ob_end_clean()
are complemented by ob_flush() and ob_clean() -
these do the same jobs as their longer cousins,
with the difference that they do not end the output buffer.
We could rewrite the previous script like this:

ob_start();
print "Hello First!\n";
ob_flush();
print "Hello Second!\n";
ob_clean();
print "Hello Third!\n";
?>

This time the buffer is flushed but left open,
then cleaned and still left open, and finally
automatically closed and flushed by PHP as the
script ends - this saves creating and destroying
output buffers. Reusing buffers like this is
about 60% faster than opening and closing buffers
all the time, and is a smart move if you ever find
yourself in this situation.



Refer this page for more PHP buffering.

Wednesday, October 20, 2010

PHP convert or parse array to object and object to array

Convert array variable to object variable.


function parseArrayToObject($array) {
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = $value;
}
}
}
return $object;
}


For multidimensional array use the below function


function array2object($data) {
if(!is_array($data)) return $data;

$object = new stdClass();
if (is_array($data) && count($data) > 0) {
foreach ($data as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = array2object($value);
}
}
}
return $object;
}


Example of php array to object conversion.

$a = array (
'index_0' => 'value_0',
'index_1' => 'value_1'
);

$o = parseArrayToObject($a);

//-- Now you can use $o like this:
echo $o->index_0;//-- Will print 'value_0'



Now let see Object to array conversion.

function parseObjectToArray($object) {
$array = array();
if (is_object($object)) {
$array = get_object_vars($object);
}
return $array;
}


For multidimensional Object use the below function

function object2array($data){
if(!is_object($data) 66 !is_array($data)) return $data;

if(is_object($data)) $data = get_object_vars($data);

return array_map('object2array', $data);
}


Example of PHP Object to Array conversion.

$o = new stdClass();
$o->index_0 = 'value_0';
$o->index_1 = 'value_1';

$a = parseObjectToArray($o);

//-- Now you can use $a like this:
echo $a['index_0'];//-- Will print 'value_0'

Monday, October 11, 2010

Implode multidimensional array in PHP

implode PHP multidimensional Array into string

Code :


public function ImplodePHPArray( $Char, $ArrayVal )
{
foreach( $ArrayVal as $Row )
{
if( is_array( $Row ) )
{
$FinalArray[] = $this -> ImplodePHPArray( $Char, $Row );
}
else
{
$FinalArray[] = $Row;
}
}
return implode( $Char, $FinalArray );
}


TESTING :

$Week = $ClassObj -> ImplodePHPArray('~^', $Week);
echo $Week;

Wednesday, September 22, 2010

Capture image through webcam and upload to server - PHP code

PHP Code for capture photo through web cam and save into your server.

take a snap through web cam and save into your database(DB)...

Source...

PHP code to capture image through webcam

PHP api to capture image through webcam.

PHP code for image capture.

download here...

real time testing page

Monday, June 21, 2010

Find Ajax Request in a Page

To find ajax request we can use the below condition.

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']))
{
//Ajax Code Here
die;
}

Sunday, May 30, 2010

Website Status Code or Error Codes Status

Web site error code status and their meaning

http://www.w3schools.com/tags/ref_httpmessages.asp

Wednesday, March 3, 2010

Solution for Reported Attack Site

Reported Attack Site!
This web site at "www.??????.com" has been reported as an attack site and has been blocked based on your security preferences.

Attack sites try to install programs that steal private information, use your computer to attack others, or damage your system.

Some attack sites intentionally distribute harmful software, but many are compromised without the knowledge or permission of their owners.

Solution:

good solutions

another solution