简体   繁体   English

PHP Json 编码 PDO::FETCH_ASSOC

[英]PHP Json Encode PDO::FETCH_ASSOC

I'm attempting to return all the rows of my MSSQL database table and spit them out in a JSON_ENCODE.我试图返回我的 MSSQL 数据库表的所有行并将它们吐出在 JSON_ENCODE 中。

When I use this and echo the $json I get a blank page.当我使用它并回显 $json 时,我得到一个空白页面。 When I do a var_dump on that var I get a bool, false.当我对该 var 执行 var_dump 时,我得到一个 bool,false。

$sth = $db->prepare("SELECT * FROM dbo.Devices");
$sth->execute();

$array = $sth->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode($array);

However, if I was to place the same fetchAll into a result var and print it, it works fine!但是,如果我将相同的 fetchAll 放入结果变量并打印它,它工作正常!

Working using print function.
$result = $sth->FetchAll();
print_r($result);

I've read of others having similar issues and that it was a UTF8 encoding issue so I attempted to do a utf8_encode on the $array before a json_encode but with the same result of a blank page.我读过其他人有类似的问题,这是一个 UTF8 编码问题,所以我尝试在 json_encode 之前在 $array 上执行 utf8_encode 但结果是空白页。 Can anyone explain this?谁能解释一下?

json_encode is character encoding sensitive. json_encode字符编码敏感。 It will fail if it can't handle the encoding.如果它无法处理编码,它将失败。 print_r is not. print_r不是。 It will happily print out whatever you give it.无论你给它什么,它都会很高兴地打印出来。

The utf8_encode fix will only work if the strings in your source data are encoded as ISO-8859-1. utf8_encode修复仅在源数据中的字符串编码为 ISO-8859-1 时才有效。 Assuming that's true it should work.假设这是真的,它应该可以工作。 Make sure you do it like this... https://stackoverflow.com/a/2790107/111755确保你这样做...... https://stackoverflow.com/a/2790107/111755

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM