nazanin
nazanin

Reputation: 749

how to get standard output json in php

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.

Upvotes: 0

Views: 305

Answers (3)

Neville
Neville

Reputation: 528

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

Upvotes: 0

Striezel
Striezel

Reputation: 3758

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.

Upvotes: 2

Wolverine
Wolverine

Reputation: 1702

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.

Upvotes: 2

Related Questions