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

时间:2016-09-16 16:09:08

标签: php json

如何从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/"
        },
]

4 个答案:

答案 0 :(得分:8)

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);

?>

enter image description here

答案 1 :(得分:1)

这是一个古老的问题,所以我认为你现在可能已经想到了这一点,但是在人们因为json_encode获得他们期望的输出而遇到问题时,这常常出现问题,所以对于未来的读者,您需要做两件事来解决这个问题:

<强> 1。格式化实际上存在,您只是在浏览器中看不到它。

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

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

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

如果您要显示某些JSON以及其他HTML内容,则可以使用其他答案中建议的<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

答案 2 :(得分:0)

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; 
}

答案 3 :(得分:0)

<?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);

Output

相关问题