Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output JSON data correctly using PHP

Tags:

json

android

php

I'm developing an Android app, and for the API I'm sending my requests to a URL that should return JSON data.

This is what I'm getting in my output: My response

And I'd like it to be displayed as Twitter response:

Twitter's JSON response

I'm assuming my response is not being parsed by the JSON Formatter Chrome extension because it's encoded badly, thus my app can't get the values I need.

Here's my PHP code:

<?php

$response = array();

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) 
{

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['decription'];

    require_once __DIR__ . '/db_connect.php';

    $db = new DB_CONNECT();

    $result = mysql_query("INSER INTO products(name, price, description) VALUES('$name', '$price', '$description')");

    if ($result) {
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        echo json_encode($response);
    } else {

        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred!";

        echo json_encode($response);
        }
} else {

    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    echo json_encode($response);

}

?>

I want to know how to display the JSON data correctly so that JSON Formatter and my android App can parse it correctly.

like image 981
Oscar Swanros Avatar asked May 17 '13 01:05

Oscar Swanros


1 Answers

Your problem is actually very easy to solve. The Chrome JSON Formatter plugin only formats your output if the Content-Type header is set to application/json.

The only thing you need to change in your code is to use header('Content-Type: application/json'); in your PHP code, before returning the json-encoded data.

like image 190
Charles Sarrazin Avatar answered Sep 20 '22 14:09

Charles Sarrazin