Returning JSON from a PHP Script

前端 未结 18 1446
南方客
南方客 2020-11-21 04:59

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

相关标签:
18条回答
  • 2020-11-21 05:25
    <?php
    $data = /** whatever you're serializing **/;
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
    ?>
    
    0 讨论(0)
  • 2020-11-21 05:25

    The answer to your question is here,

    It says.

    The MIME media type for JSON text is application/json.

    so if you set the header to that type, and output your JSON string, it should work.

    0 讨论(0)
  • 2020-11-21 05:26

    Yeah, you'll need to use echo to display output. Mimetype: application/json

    0 讨论(0)
  • 2020-11-21 05:27

    If you query a database and need the result set in JSON format it can be done like this:

    <?php
    
    $db = mysqli_connect("localhost","root","","mylogs");
    //MSG
    $query = "SELECT * FROM logs LIMIT 20";
    $result = mysqli_query($db, $query);
    //Add all records to an array
    $rows = array();
    while($row = $result->fetch_array()){
        $rows[] = $row;
    }
    //Return result to jTable
    $qryResult = array();
    $qryResult['logs'] = $rows;
    echo json_encode($qryResult);
    
    mysqli_close($db);
    
    ?>
    

    For help in parsing the result using jQuery take a look at this tutorial.

    0 讨论(0)
  • 2020-11-21 05:28

    While you're usually fine without it, you can and should set the Content-Type header:

    <?php
    $data = /** whatever you're serializing **/;
    header('Content-Type: application/json');
    echo json_encode($data);
    

    If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

    0 讨论(0)
  • 2020-11-21 05:32

    If you need to get json from php sending custom information you can add this header('Content-Type: application/json'); before to print any other thing, So then you can print you custome echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

    0 讨论(0)
提交回复
热议问题