doumeng3345 2014-12-21 22:06
浏览 35

PHP Json_encode - 没有关于特定列MySQL的json数据

I am trying to make a simple journalview app for iPhone using a mysql DB. I am using php to connect to the db and encode the data to json. I am using a very simple db with 3 columns:

  • id
  • subject
  • message

When I select the id and subject from the table, the JSON data is displayed correctly. When I select everything or I select the message alone, I only see a white screen. The message column is of datatype text and should be able to have strange signs (/,\,¨,$,%, spaces, lines,...) The only way I can get the message data to display is by doing the following in my connection file:

while($r = mysql_fetch_assoc($resultset))
        {

        //$r = preg_replace("!?
!", " ",$r);
        $r= json_encode($r);

            $records[] = $r;

        }

        //Output the data as JSON

        echo json_encode($records);
    }


}

However, the data that is returned is full of backslashes, , and does not seem like valid json:

[{"id":"248","subject":"General","message":"Dear Diary

This is a test.
Does it work       or not?!

Goodbye.


D"},{"id":"249","subject":"General","message":"Hi

This is Test number 2.
Does it Work?

\/\/ goodbye \\\\"}]

If i empty my message column and put in normal text without special signs it works fine, so I'm guessing that is the issue. I would be better however if a message could contain special characters and backslashes, is this possible or not?

  • 写回答

1条回答 默认 最新

  • dongqiao3833 2014-12-21 22:43
    关注

    The and are valid and they are fine. They are hidden chartaters, they are stored this way in your database also so you have 2 options. Clean the database with the below function or clean the item before putting it into json with it.

    function clean($string) {
       $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    
       return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    }
    

    if you want to keep the special characters escape them Parsing JSON containing new line characters

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入