Home » Coding

[PHP] MySQL result to JSON – For mongoDB

9 May 2012 No Comment

So today i tested mongoDB and i wanted some rows from an existing database but it had to be in JSON format so i wrote this little script to port it.

 

<?php
set_time_limit(0);
mysql_connect('localhost','root','mypassword');
mysql_select_db('database_name');
mysql_query("SET NAMES 'utf8';");
$m = mysql_query('SELECT * FROM `table` LIMIT 0,100;');
$json = "";
$i = 0;
while($rows[] = mysql_fetch_assoc($m)){
	$json .= json_encode($rows[$i]);
	$json .= "\n";
	$i++;
}
$fp = fopen('data.json', 'a+');
fwrite($fp, $json);
fclose($fp);
?>

Your opinion matters!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.