如何将 PDOStatement
转换为 JSON?
我需要将 PDO::FETCH_OBJ
转成 JSON 格式。
json_encode
无法直接将 PDO::FETCH_OBJ
转为 JSON 格式。
你可以使用内置的 PHP 函数 json_encode() http://php.net/manual/en/function.json-encode.php
要编码结果,可以使用类似下面的代码:
<?php
$pdo = new PDO("mysql:dbname=database;host=127.0.0.1", "user", "password");
$statement = $pdo->prepare("SELECT * FROM table");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
utf8_unicode_ci
的MySQL数据库。由于某种原因,json_encode告诉我,“格式不正确的UTF-8字符,可能是编码不正确”。我不得不将$results
数组转换为Unicode(再次?),现在它可以正常工作了。 - SmamattifetchAll()
方法来检索一个值的数组,然后将其传递给json_encode()
。$resultJSON = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
$array = $statement->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $array );
尝试这个,也许可以帮助你
$data = array();
if($stmt->execute()){
while ($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$data['data'] = $row;
}
}
}
if(!empty($data)){
header("Access-Control-Allow-Origin: *");//this allows cors
header('Content-Type: application/json');
print json_encode($data);
}else{
echo 'error';
}
我也发现在通过json_encode()返回JSON对象之前插入并设置PHP头文件('Content-Type: application/json')非常有用。
PDOStatement
? - Anthony Forloney