0

I am working PHP and MySQL. I am created a database and table. I want to convert table to JSON. So, I write this code block:

<?php

    include "../config/database.php";

        $SQLUser = "SELECT * FROM tbl_user";  
        $SQLUserResult =mysqli_query($Conn,$SQLUser );
        $JSON= array();

        while($row=mysqli_fetch_assoc($SQLUserResult ))
        {
            $JSON[] = $row;
        }
        $Show =  json_encode($JSON);
        echo count($JSON);
        echo $Show;
?>

When run this page, I take JSON size correctly. But I can't display JSON values. What can I do?

In the page source, I see the count of rows in my JSON array (13), but no data.

Adding var_dump($row); shows me something like

array(13) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(1) "A" ["surname"]=> string(1) "A" } [1]=> array(3) { ...

The encoding is utf8_general_ci.

1
  • Instead of your while loop, you could use $JSON = mysqli_fetch_all($SQLUserResult); to get all the rows. Furthermore I don't see why it doesn't work. Commented Aug 7, 2019 at 23:20

1 Answer 1

3

I think, your database or tables returns probably a faulty response, some strings were probably not UTF-8. So, You can create a function for convert UTF-8.

function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
}

Than, you can encode just like this:

echo json_encode(utf8ize($JSON));
Sign up to request clarification or add additional context in comments.

1 Comment

Also you can check your file encoding, should be UTF 8 w/o BOM

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.