json_encode is returning NULL?

前端 未结 10 1939
[愿得一人]
[愿得一人] 2020-11-22 12:22

For some reason the item \"description\" returns NULL with the following code:



        
相关标签:
10条回答
  • 2020-11-22 12:44

    For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable on entities.

    0 讨论(0)
  • 2020-11-22 12:57

    For anyone using PDO, the solution is similar to ntd's answer.

    From the PHP PDO::__construct page, as a comment from the user Kiipa at live dot com:

    To get UTF-8 charset you can specify that in the DSN.

    $link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");

    0 讨论(0)
  • 2020-11-22 12:58

    I bet you are retrieving data in non-utf8 encoding: try to put mysql_query('SET CHARACTER SET utf8') before your SELECT query.

    0 讨论(0)
  • 2020-11-22 12:59

    AHHH!!! This looks so wrong it hurts my head. Try something more like this...

    <?php
    include('db.php');
    
    $result = mysql_query('SELECT `id`, `name`, `description`, `icon` FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
    $rows = array();
    while($row = mysql_fetch_assoc($result)){
        $rows[] = $row;
    }
    
    echo json_encode($rows);
    ?>
    
    • When iterating over mysql_num_rows you should use < not <=. You should also cache this value (save it to a variable) instead of having it re-count every loop. Who knows what it's doing under the hood... (might be efficient, I'm not really sure)
    • You don't need to copy out each value explicitly like that... you're just making this harder on yourself. If the query is returning more values than you've listed there, list only the ones you want in your SQL.
    • mysql_fetch_array returns the values both by key and by int. You not using the indices, so don't fetch em.

    If this really is a problem with json_encode, then might I suggest replacing the body of the loop with something like

    $rows[] = array_map('htmlentities',$row);
    

    Perhpas there are some special chars in there that are mucking things up...

    0 讨论(0)
提交回复
热议问题