简体   繁体   中英

PHP json_encode() returns nothing

OK, few days ago I wrote a block of code in Java that sends post requests to a PHP file in order to store some data in a MySQL database and receive back simple json_encode() strings such as "error_101" responses from PHP and it worked just fine. Yesterday I reinstalled my XAMPP because I've had some problems with openssl PHP extention and now none of my json_encode() reponses return a value. I've checked the phpinfo() and it says that json support is enabled. To mention that values sent to PHP from JAVA are JSON objects as well and the json_decode() works just fine!

Here's my code to send responses from PHP to JAVA:

<?php 
    header('Content-type: application/json');
    echo json_encode("error_101");
?>

Here's the code to get the response in JAVA

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);

String url = "http://192.168.254.19/android/register.php";

HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();

String result = null;
if (entity != null) {
    InputStream instream = entity.getContent();

    InputStreamReader is_reader = new InputStreamReader(instream);
    BufferedReader br = new BufferedReader(is_reader);
    result = br.readLine();
    Log.i("Read from server", result);
    Toast.makeText(this,  result, Toast.LENGTH_LONG).show();
}

The response I'm getting is " <br /> "

You sure you don't have some debug code somewhere up the chain that reads

echo $TesttVar1 . '<br />';

That would also stop the "header()" from working. Turn on ALL errors (error_reporting(E_ALL); ini_set('display_errors', 'on'); ) and that will show you the line the
is output, if that's the case.

But to help weed it out if it is json_encode, just return "Error_101" without the function to test. But I don't think you're getting that far down the program.

json_encode needs an array. like

json_encode(array('status'=>'error_101'));

in this case:

header("Content-type: text/html");
echo json_encode("error_101");

it works.

in this other case:

header("Content-type: application/json");
echo json_encode("error_101");

it doesn't work.

It seems a bug!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM