【问题标题】:Use JSON to print in readable format PHP & Android使用 JSON 以可读格式打印 PHP & Android
【发布时间】:2018-02-21 20:46:14
【问题描述】:

我从事项目以从 db 获取数据并在 Android 应用程序中呈现/显示它 我在 php 和 mysql 上工作

在php文件中我写了这个

<?php

$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM table";

$result = $conn->query($sql);

if ($result->num_rows >0) {


 while($row[] = $result->fetch_assoc()) {

 $x = $row;


 $json = json_encode($x, JSON_PRETTY_PRINT);

代码如下所示 当我在浏览器上运行它时它可读但没有中断 像这样显示

{"data":{"sender":"Jhon Andrew","recipient":"Someone OverThe Internet","message":"Lorem ipsum dolor sit amet."}}

我希望它像这样显示

{
    "data": {
        "sender":"Jhon Andrew",
        "recipient":"Someone OverThe Internet",
        "message":"Lorem ipsum dolor sit amet."
    }
}

为什么当我在浏览器中运行代码时以可读格式显示但没有中断 它会在安卓系统中显示吗?

【问题讨论】:

  • 浏览器不呈现换行符或多个空格。包裹在&lt;pre&gt; 标签中或使用highlight_string()
  • Android 上的应用程序使用 JSON,还是仅仅显示?
  • 相同的代码
  • 你读过第一条评论吗?
  • $json = json_encode($tem, JSON_UNESCAPED_UNICODE,JSON_PRETTY_PRINT); 实际上应该是 $json = json_encode($tem, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

标签: php android mysql json


【解决方案1】:

您需要if。相同的 URL,但带有用于在网络上显示的参数。

假设 JSON 的 URL 是 http://example.com/service.php,它返回一个有效的 JSON。您可以使用参数来更改显示,例如http://example.com/service.php?view

然后,在您的代码中:

if (isset($_GET['view'])) {
    highlight_string($json) ; // As @AbraCadaver suggested
} else {
    echo $json ; // Valid JSON for the service.
}

【讨论】:

  • 我的php文件所有显示保存在数据库中的数据的工作不会插入任何信息
  • 我可以用这个 $json = json_encode($tem, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  • 使用 if 将仅与 @AbraCadaver 建议
  • @karimsemsssm 是的,我想。
【解决方案2】:

在 chrome 中使用此 plugin 以获得所需的格式化输出

它会在安卓系统中显示吗?

例如,如果您只想在TextView 中显示它,它将不会按您的意愿显示。但它会被包裹起来。

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2015-03-18
    • 2020-12-03
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2020-07-02
    • 2017-04-11
    相关资源
    最近更新 更多