简体   繁体   中英

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.

When I use this and echo the $json I get a blank page. When I do a var_dump on that var I get a 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!

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. Can anyone explain this?

json_encode is character encoding sensitive. It will fail if it can't handle the encoding. print_r is not. 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. Assuming that's true it should work. Make sure you do it like this... https://stackoverflow.com/a/2790107/111755

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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