0

I have a Java Program that sends a HTTP POST request to a PHP file. I need the PHP script to extract the JSON data to some variables and call a PHP function with those variables (parameters). Please find the PHP code below.

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $data = json_decode(file_get_contents("php://input"), true);
        var_export($data);      
    }
    else
    {
        var_export($_SERVER['REQUEST_METHOD']);
    }
?> 

The JSON Object created in Java

JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));

Please help me understand how to extract the JSON array data to variables And how to make the call.

Pritam
  • 39
  • 5
  • What is your code doing right now? – Matt Mar 01 '16 at 02:28
  • It is returning the JSON array to Java Program. I want the PHP script to make a call to a PHP function. – Pritam Mar 01 '16 at 02:31
  • 1
    What's wrong with calling the function? `callWhateverFunction($data);` http://stackoverflow.com/questions/8893574/php-php-input-vs-post – Matt Mar 01 '16 at 02:32

1 Answers1

0

Once you've run json_decode(), $data is just a "normal" php array with "normal" php values in it.
So, e.g.

/*
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
=>
*/
// $input = file_get_contents("php://input");
$input = '{"name":"Dash","num":100,"balance":1000.21}';

$data = json_decode($input, true);
$response = array(
    'name_rev'      => strrev($data['name']),
    'num_mod_17'    => $data['num'] % 17,
    'balance_mul_2' => $data['balance'] * 2
);
echo json_encode($response, JSON_PRETTY_PRINT); // you might want to get rid off JSON_PRETTY_PRINT in production code

prints

{
    "name_rev": "hsaD",
    "num_mod_17": 15,
    "balance_mul_2": 2000.42
}

two more tips:

Community
  • 1
  • 1
VolkerK
  • 95,432
  • 20
  • 163
  • 226