douzhi7082 2017-03-22 17:38
浏览 51

阅读JSON / PHP / Android中的段落

I am developing an Android app and I am new to all of this. My data is stored in MySQL on a web server and I am using a PHP script to read data from MySQL and convert to JSON string which then accessed by Android JSON object in my mobile app. All was working fine until I had multiple paragraphs in my MySQL database. When I read MySQL data using PHP and convert that to JSON string, all the paragraphs become one large paragraph. Android app is reading data correctly, but the problem is I still need to read multiple paragraphs as stored in MySQL database. Could anyone guide me to the right direction or sort this out? Help would be appreciated.

Below is the script files in PHP I am using to read MySQL data and convert that to JSON string.

Connection File:

<?php
$db_name = "myDbName";
$mysql_username = "db_user";
$mysql_password = "db_password";
$server_name = "serverName";

$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);


$sSQL= 'SET CHARACTER SET utf8';

mysqli_query($conn, $sSQL) or die ('Can\'t charset in DataBase'); 

if(!$conn)
{
    die("Connection failed:" . mysqli_error($conn));
}

?>

Json coversion file:

<?php
require "conn.php";

$sql_qry = "SELECT * FROM tabITArticles;";

$result = mysqli_query($conn, $sql_qry);

$response = array();

while($row = mysqli_fetch_array($result)){

array_push($response, array("id"=>$row[0],"title"=>$row[1],"author"=>$row[2],"content"=>$row[3],"image"=>$row[4],"date"=>$row[5]));
}

echo json_encode(array("server_response"=>$response));

mysqli_close($conn);
?>
  • 写回答

1条回答 默认 最新

  • doormen2014 2017-03-22 18:21
    关注

    There are a few things you can do to keep the paragraphs.

    When retrieving the information from the database you can do:

    $arr = explode(PHP_EOL, $row[3]);
    

    This will split the string in an array, and then you can pass it. Then you retrieve it in android as an array.

    Another option is to encode the new lines in php using a combination like and .

    $str= str_replace(PHP_EOL, '
    ', $row[3]);
    

    Then in android you can split the string and store it in an array.

    String[] str= stringfromjson.split("
    ");
    
    评论

报告相同问题?