Converting PHP result array to JSON


Question

I want to convert my result array to JSON format in PHP. Here is my code:

$row = mysql_fetch_array($result)

I want to convert $row to JSON format and pass the JSON data to an jQuery plugin.

1
26
4/5/2017 5:40:55 AM

Accepted Answer

json_encode is available in php > 5.2.0:

echojson_encode($row);

55
1/31/2014 2:55:26 PM

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon