1

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?

5
  • You don't use PDO::FETCH_ASSOC in the second example. Does removing that option allow you to json_encode() the result? Commented May 5, 2016 at 15:03
  • No, I get a blank page when removing that as well. Commented May 5, 2016 at 15:05
  • Wait, are you getting a blank page because you're not printing out the json_encoded results? print_r prints to screen, json_encode does not. Commented May 5, 2016 at 15:09
  • I'm doing an echo on the results. Commented May 5, 2016 at 15:11
  • Why do you think it's an encoding issue? What does your data look like? Commented May 5, 2016 at 21:36

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.