简体   繁体   中英

PHP: json_encode() doesn't show anything with multidimensional array

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.

This is my code:

<?php
    $servername = "localhost:3036";
    $username = "example_user";
    $password = "example_password";

    $conn = mysql_connect($servername, $username, $password);

    if(! $conn) {
        die("Could not connect: " . mysql_error());
    }

    $sql = "SELECT * FROM table_name";
    mysql_select_db("database_name");
    $retval = mysql_query($sql, $conn);

    if(! $retval) {
        die("Could not get data: " . mysql_error());
    }

    while($row = mysql_fetch_assoc($retval)) {
        $output[]=$row;
    }

    print(json_encode($output));
    mysql_close($conn);
?>

This just gives a blank page as output (error messages are set to display). However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array .

This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.

User @Joni led me to the solution.

Adding mysql_set_charset("utf8") fixed my issue.

As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes? .

尝试

 echo json_encode($output) ;

It seems you have some utf8 character in your result set

add this statement before running your query

mysql_query('SET CHARACTER SET utf8');

Update

"mysql"

to

"mysqli"

and add

mysqli_set_charset($variável_de _conexão, 'utf8');

below the connection variable

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