0

I want to get a JSON output like http://api.androidhive.info/json/movies.json and I wrote this code in PHP:

<?php
    $con=mysqli_connect("localhost","root","","ebrahim");
    $sql="SELECT * FROM movie";
    $result=mysqli_query($con,$sql);
    $response= array();
    while($row=mysqli_fetch_array($result,MYSQLI_NUM)){
        $product = array();
        $product["title"]=$row[1];
        $product["image"]=$row[2];
        $product["rating"]=$row[3]; 
        $product["releaseyear"]=$row[4]; 
        $product["genre"]=$row[5];   
        array_push($response,$product);
    }
    echo json_encode($response);
?>

but my output is like this : enter image description here

Please help me to make a standard JSON.

1
  • 2
    Set your header properly header('Content-Type: application/json'); Commented Dec 17, 2016 at 21:12

3 Answers 3

2

echo json_encode($response, JSON_PRETTY_PRINT);

Pass JSON_PRETTY_PRINT constant as the second parameter to the json_encode function.

Also, set content type of the response to JSON format with the following code:

header('Content-Type: application/json');

So, browsers recognize the response is a JSON resource.

Sign up to request clarification or add additional context in comments.

Comments

2

I'm not exactly sure what you mean by "standard" JSON. Your output is already JSON. However, if you want to give the browser (or any other client) a hint about the content, set the proper content type. As Bart pointed out, this can be done by adding the appropriate header:

header('Content-Type: application/json');

Additionally, if you want the "nice" formatting of the JSON output, use the options parameter of json_encode: The option JSON_PRETTY_PRINT should help to achieve that. So instead of echo json_encode($response); you should put

echo json_encode($response, JSON_PRETTY_PRINT);

into your script. JSON_PRETTY_PRINT is available since PHP 5.4.

Comments

0

PHP has a function for it. Use JSON_PRETTY_PRINT you can read more about it here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.