Why Your PHP JSON Output Looks Broken and How to Fix It
When an Android app sends a request to your API and receives a response that doesn't parse correctly, the issue is almost never about the json_encode() function itself. In most cases, the problem stems from how the server transmits the data headers. Based on the symptoms describedâwhere the data appears mangled in tools like JSON Formatter but works logicallyâit is highly probable that your PHP script is outputting HTML content before or instead of the raw JSON string, or it is missing the critical HTTP header that tells the client to expect JSON.
The Missing Header
The most common cause of this specific issue is the absence of the Content-Type header. When you call echo json_encode($response);, PHP generates a valid JSON string. However, if the browser or your Android app does not explicitly know that the response body contains JSON, it might attempt to render it as HTML or treat it as plain text depending on its own configuration.
You must explicitly set the content type before any output is sent. This needs to happen at the very top of your script, before any logic or echo statements. Use the following code structure:
<?php
header('Content-Type: application/json');
// No echo or print statements allowed here yet
?>
By setting this header, you signal to the HTTP client that the payload is strictly JSON. This ensures that tools like Postman, Chrome extensions, and Android OkHttp clients parse the response stream as structured data rather than trying to interpret it as a document. Without this header, some clients might prepend their own formatting or fail to decode the structure entirely, leading to the "garbled" appearance you are seeing in your screenshots.
Security Vulnerabilities in the Provided Code
While fixing the headers is the immediate step to get your Android app working, the provided PHP code contains critical security flaws that must be addressed before deploying this API to production. The script uses mysql_query with direct variable interpolation inside the SQL string:
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
This approach is extremely dangerous and deprecated. It exposes your application to SQL Injection attacks. An attacker can craft a malicious name or description parameter to alter the query structure, potentially exposing your database or inserting arbitrary commands. Furthermore, the mysql_* extension has been removed from PHP as of version 5.5.0.
To resolve this and secure your API, you should switch to PDO or MySQLi with prepared statements. This separates the data from the SQL logic, ensuring that user input is always treated strictly as a value, not as part of the command syntax.
Here is how to refactor the insertion logic securely:
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$stmt = $db->prepare("INSERT INTO products(name, price, description) VALUES(:name, :price, :description)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':price', $price);
$stmt->bindParam(':description', $description);
// Execute the statement
$stmt->execute();
Handling Errors and HTTP Status Codes
Your current code echoes a JSON response regardless of success or failure, but it relies solely on the JSON content to indicate status. Best practice in RESTful API design is to use HTTP status codes to communicate the outcome of the request.
If the database insert succeeds, send a 201 Created or 200 OK status. If the required fields are missing, send a 400 Bad Request. If a SQL error occurs, send a 500 Internal Server Error. Most HTTP clients and frameworks on the Android side will check the status code first before even parsing the body. This allows for better error handling logic in your mobile app without needing to parse the entire JSON payload just to determine if the request was valid.
You can set this using PHP's built-in functions:
if ($result) {
http_response_code(201); // Created
} else {
http_response_code(500); // Internal Server Error
}
echo json_encode($response);
By combining the correct Content-Type header, secure database interactions, and proper HTTP status codes, your API will return a response that is not only readable by Chrome extensions but also robust enough for production Android applications. For developers looking to build more scalable APIs without managing these low-level details manually, frameworks like Laravel offer built-in middleware and controllers that handle headers, routing, and security out of the box.