I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type
header?
<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>
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.
Yeah, you'll need to use echo to display output. Mimetype: application/json
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.
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).
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.'"}';