在PHP中将PDO记录集转换为JSON

use*_*450 1 php json pdo recordset

我使用PHP,我需要一种方法将整个记录集转换为JSON字符串.

在搜索Stack Overflow时,我发现这个解决方案有效:

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);
}
Run Code Online (Sandbox Code Playgroud)

这段代码的问题是我发现mysql_fetch_assoc()在PHP 5.5.0中不推荐使用该函数.另一件事是我使用PDO连接到我的数据库.

鉴于上述情况,将PDO记录集转换为JSON的最佳解决方案是什么?我希望它也适用于PHP的更高版本.

use*_*450 15

解决方案很简单.考虑到变量$stmt是您的PDO记录集,您可以将其转换为JSON,如下所示:

json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
Run Code Online (Sandbox Code Playgroud)

有关此代码中使用的函数的更多信息:

http://www.php.net/manual/en/function.json-encode.php

http://www.php.net/manual/en/pdostatement.fetchall.php