繁体   English   中英

如何使用PHP执行JSON漂亮打印

[英]How to do JSON pretty print with PHP

如何从MySQL执行JSON漂亮打印? 我在代码中使用了JSON_PRETTY_PRINT ,但是没有打印出我期望的结果。 我当前的脚本是:

<?php   
//open connection to mysql db
$connection = mysqli_connect("127.0.0.1","root","Kunal@7890","testdb") or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db
$sql = "select id,title,profilepic,created_at,url from news";

$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;

    print json_encode($rows, JSON_PRETTY_PRINT);

}
?>

对于此脚本,我得到的结果如下:

[ { "id": "1", "title": "test", "profilepic": "0", "created_at": "2016-09-05 12:11:17", "url": "0" } ][ { "id": "1", "title": "test", "profilepic": "0", "created_at": "2016-09-05 12:11:17", "url": "0" }, { "id": "2", "title": "JCECE", "profilepic": "http:\/\/results.jharkhandeducation.net\/JCECEB\/JCECEB-Logo.jpg", "created_at": "2016-09-16 10:14:55", "url": "https:\/\/jcece.co.in\/" } ]

我希望我的结果先打印表名,然后再打印列,如下所示:

{
    "news": [
     {
            "id": 36,
            "name": "JCECE",
            "image": null,
            "status": " JCECE 2016 will be conducted on June 5, 2016 by JCECE Board, which is the exam conducting authority for the engineering entrance examination. JCECE 2016 will be conducted to offer admissions to undergraduate engineering courses at the participating institutes of JCECE 2016 in the state of Jharkhand. As of now, there are a total of 19 colleges (government+private) that will offer over 6000 B.E/B.Tech seats to aspiring candidates in Jharkhand. 

Application Dates:16 Apr 2016 to 16 May 2016

Admit Card Date:11 May 2015

Exam Dates:05 Jun 2016

Result Date:01 Jul 2015 to 10 Jul 2015       ",
            "profilePic": "http://results.jharkhandeducation.net/JCECEB/JCECEB-Logo.jpg",
            "timeStamp": "1461323436930",
            "url": "https://jcece.co.in/"
        },
    {
            "id": 39,
            "name": "THAPAR UNIVERSITY",
            "image": null,
            "status": "The details about the Thapar University B.Tech admission 2016 have been released. The admission will be held as per the JEE Main 2016 score but candidates will have to fill a separate application form for it. Interested candidates, who are also eligible, may access the link below to apply. The last date to submit the application form is 26 April 2016.

Last Date:26 Apr 2016",
            "profilePic": "https://upload.wikimedia.org/wikipedia/commons/d/da/ThaparUniversityLogo.jpg",
            "timeStamp": "1459595788930",
            "url": "http://www.thapar.edu/"
        },
]

json_encode($rows,JSON_PRETTY_PRINT); 返回带有换行符的美化数据。 这对于命令行输入很有帮助,但是正如您所发现的那样,它在浏览器中看起来并不漂亮。 浏览器将接受换行符作为源(因此,查看页面源确实会显示漂亮的JSON),但是它们不用于在浏览器中格式化输出。 浏览器需要HTML。

理想情况下,应该使用<pre>标记包装输出。 这将在浏览器中以与在源中表示相同的方式表示它。

如果由于某些原因这还不够用,您还可以考虑用适当的<br>标记替换换行符。 但是,这会丢失使用空格进行的某些格式化。

<?php

$data = array(
    'foo' => array(
        'bar',
        'baz'
    )
);

$jsonData = json_encode($data, JSON_PRETTY_PRINT);

echo "<h1>Original</h1>";
echo $jsonData;

echo "<h1>&lt;pre&gt;</h1><br>";
echo "<pre>" . $jsonData . "</pre>";

echo "<h1>str_replace()</h1><br>";
echo str_replace("\n", "<br>", $jsonData);

?>

在此处输入图片说明

有点老问题了,所以我想您可能已经知道了,但这在人们很难从json_encode获得期望输出的问题中经常出现,所以对于将来的读者来说,有两个问题要解决此问题,需要做的主要事情:

1.格式实际上在那里,您只是在浏览器中看不到它。

JSON_PRETTY_PRINT添加的所有新行和缩进通常不会在您的浏览器中显示,但是如果您查看页面源代码,它们将在那里。 除非另行指定,否则您的PHP输出可能会使用Content-Type:text/htmlContent-Type:text/html送到浏览器,因此浏览器会将页面解释为HTML文档,这意味着它将折叠所有空白(换行和缩进)中的单个空格,这就是为什么您只在屏幕上看到一行的原因。

如果脚本的整个输出是JSON,则可以在顶部添加标头以指定该标头,这样浏览器就会知道它不是HTML。

header('Content-type: Application/JSON');

如果您有要与其他HTML内容一起显示的JSON,则可以按照其他答案中的建议使用<pre>标记。

echo '<pre>'. json_encode($people, JSON_PRETTY_PRINT) . '</pre>';

2.在获取所有行之前不要编码。

这是问题的另一部分:

while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
    print json_encode($rows, JSON_PRETTY_PRINT);
}

如果要以JSON输出查询结果,则必须等到提取所有结果后再对它们进行编码

使用上面的代码,您要获取一行,将其附加到数组中,然后立即为查询结果中的每一行打印整个JSON编码的数组。 改为这样做。

while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;                               // add rows to array
}
print json_encode($rows, JSON_PRETTY_PRINT);    // encode and print full array

1- json_encode($rows,JSON_PRETTY_PRINT); 返回带有换行符的美化数据。 这对于命令行输入很有帮助,但是正如您所发现的那样,它在浏览器中看起来并不漂亮。 浏览器将接受换行符作为源(因此,查看页面源确实会显示漂亮的JSON),但是它们不用于在浏览器中格式化输出。 浏览器需要HTML。

2-使用此功能github

<?php
/**
 * Formats a JSON string for pretty printing
 *
 * @param string $json The JSON to make pretty
 * @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
 * @return string The prettified output
 * @author Jay Roberts
 */
     function _format_json($json, $html = false) {
    $tabcount = 0; 
    $result = ''; 
    $inquote = false; 
    $ignorenext = false; 
    if ($html) { 
        $tab = "&nbsp;&nbsp;&nbsp;"; 
        $newline = "<br/>"; 
    } else { 
        $tab = "\t"; 
        $newline = "\n"; 
    } 
    for($i = 0; $i < strlen($json); $i++) { 
        $char = $json[$i]; 
        if ($ignorenext) { 
            $result .= $char; 
            $ignorenext = false; 
        } else { 
            switch($char) { 
                case '{': 
                    $tabcount++; 
                    $result .= $char . $newline . str_repeat($tab, $tabcount); 
                    break; 
                case '}': 
                    $tabcount--; 
                    $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char; 
                    break; 
                case ',': 
                    $result .= $char . $newline . str_repeat($tab, $tabcount); 
                    break; 
                case '"': 
                    $inquote = !$inquote; 
                    $result .= $char; 
                    break; 
                case '\\': 
                    if ($inquote) $ignorenext = true; 
                    $result .= $char; 
                    break; 
                default: 
                    $result .= $char; 
            } 
        } 
    } 
    return $result; 
}
<?php
$conn = mysqli_connect("localhost","root","","mydatabase");

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

$result = mysqli_query($conn,"SELECT * FROM tblUser");

$data = array();

while ($row = mysqli_fetch_array($result)) {
    array_push($data, array('userId'=> $row['userId'],'firstName'=> $row['firstName'], 'lastName'=>$row['lastName'],
        'email'=>$row['email'], 'phoneNumber'=>$row['phoneNumber'], 'userImage'=>"user_images/".$row['userImage']));
}


$return['status']  = true;
$return['message'] = 'Success';
$return['data']    = $data;
header('Content-Type: application/json');
echo json_encode($return, JSON_PRETTY_PRINT);
$conn->close();

?>

这两行将以漂亮的格式打印

header('Content-Type: application/json');
echo json_encode($return, JSON_PRETTY_PRINT);

输出量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM