在PHP中将PDO记录集转换为JSON [英] Convert PDO recordset to JSON in PHP
问题描述
我正在使用PHP,我需要一种将整个记录集转换为JSON字符串的方法.
Im using PHP and I need a way to convert an entire recordset to a JSON string.
在搜索堆栈溢出时,我发现此解决方案有效:
While searching Stack Overflow I found this solution that works:
function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you don´t really need to do anything here.
}
return json_encode($rs);
}
此代码的问题是我发现PHP 5.5.0中不推荐使用函数mysql_fetch_assoc()
.另一件事是,即时通讯使用PDO连接到我的数据库.
The problem with this code is that I found that the function mysql_fetch_assoc()
is deprecated in PHP 5.5.0. Another thing is that im using PDO to connect to my database.
鉴于上述情况,将PDO记录集转换为JSON的最佳解决方案是什么?我也希望它也可以在更高版本的PHP中使用.
Given the circunstances above, what would be the best solution to convert a PDO recordset to JSON? I want it to work at later versions of PHP too.
推荐答案
解决方案很简单.
考虑到变量$stmt
是您的PDO记录集,可以将其转换为JSON,如下所示:
The solution is simple.
Considering that the variable $stmt
is your PDO recordset, you can convert it to JSON like this:
json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
有关这段代码中使用的功能的更多信息:
For more info about the functions used in this piece of code:
http://www.php.net/manual/en/function.json-encode .php
http://www.php.net/manual/en/pdostatement.fetchall.php
这篇关于在PHP中将PDO记录集转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!