使用PHP将数据从MYSQL转换为JSON
我有以下非常简单的测试PHP代码,该代码提取数据并将其放入JSON格式的文本中.
I have the following quite simple test PHP code that extracts the data and puts it into JSON formatted text.
我收到以下错误.
致命错误:在第33行的/var/www/test.php中,允许的内存大小为33554432字节已用尽(试图分配1979603字节)
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 1979603 bytes) in /var/www/test.php on line 33
第33行是json_encode()
行.
有没有办法使它更有效? PHP.ini
已被设置为最大32M,因此从8M标准开始可以调整大小!
Is there a way to make this more efficient? The PHP.ini
is already set to 32M as max, hence sized up from the 8M standard!
<?php
require('../../admin/db_login.php');
$db=mysql_connect($host, $username, $password) or die('Could not connect');
mysql_select_db($db_name, $db) or die('');
$result = mysql_query("SELECT * from listinfo") or die('Could not query');
$json = array();
if(mysql_num_rows($result)){
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
// cast results to specific data types
$test_data[]=$row;
}
$json['testData']=$test_data;
}
mysql_close($db);
echo json_encode($json);
?>
您可能正在编码非常大的数据集.您可以对每一行进行编码,而不是一次大的操作即可对每一行进行编码.
You are probably encoding a very large dataset. You could encode each row, one row at a time instead of encoding it in one big operation.
<?php
require('../../admin/db_login.php');
$db=mysql_connect($host, $username, $password) or die('Could not connect');
mysql_select_db($db_name, $db) or die('');
$result = mysql_query("SELECT * from listinfo") or die('Could not query');
if(mysql_num_rows($result)){
echo '{"testData":[';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
// cast results to specific data types
if($first) {
$first = false;
} else {
echo ',';
}
echo json_encode($row);
}
echo ']}';
} else {
echo '[]';
}
mysql_close($db);
这样,每次对json_encode()
的调用仅编码一个小数组,而不是一个大数组.最终结果是相同的. 这是IMO解决方案,它将使用较少的内存.
That way, each call to json_encode()
only encodes a small array instead of a large one. The end result is the same. This is IMO the solution which will use the less memory.