MOOD-printen JSON met PHP

Ik bouw een PHP-script dat JSON-gegevens naar een ander script voedt. Mijn script bouwt gegevens op in een grote associatieve array en voert vervolgens de gegevens uit met json_encode. Hier is een voorbeeldscript:

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);

De bovenstaande code levert de volgende uitvoer op:

{"a":"apple","b":"banana","c":"catnip"}

Dit is geweldig als je een kleine hoeveelheid gegevens hebt, maar ik heb de voorkeur aan iets in deze regels:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Is er een manier om dit in PHP te doen zonder een lelijke hack? Het lijkt erop dat iemand bij Facebook ontdekt. ​​


Antwoord 1, Autoriteit 100%

PHP 5.4 biedt de JSON_PRETTY_PRINToptie voor gebruik met de json_encode()CALL.

http://php.net/mannual/en/function.json- coderen.php

<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

Antwoord 2, Autoriteit 15%

Deze functie neemt JSON-string en inspringing het erg leesbaar. Het moet ook convergerend zijn,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

Invoer

{"key1":[1,2,3],"key2":"value"}

Uitgang

{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

Code

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );
    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;
                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;
                case ':':
                    $post = " ";
                    break;
                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }
    return $result;
}

Antwoord 3, autoriteit 8%

Veel gebruikers stelden voor om

echo json_encode($results, JSON_PRETTY_PRINT);

Wat volkomen juist is. Maar het is niet genoeg, de browser moet het type gegevens begrijpen, u kunt de koptekst specificeren net voordat u de gegevens terugstuurt naar de gebruiker.

header('Content-Type: application/json');

Dit resulteert in een goed opgemaakte uitvoer.

Of, als je van extensies houdt, kun je JSONView voor Chrome gebruiken.


Antwoord 4, autoriteit 4%

Ik realiseer me dat deze vraag gaat over het coderen van een associatieve array naar een mooi opgemaakte JSON-tekenreeks, dus dit is niet direct een antwoord op de vraag, maar als je een tekenreeks hebt die al in JSON-formaat is, kun je het vrij eenvoudig door het te decoderen en opnieuw te coderen (vereist PHP >= 5.4):

$json = json_encode(json_decode($json), JSON_PRETTY_PRINT);

Voorbeeld:

header('Content-Type: application/json');
$json_ugly = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_pretty = json_encode(json_decode($json_ugly), JSON_PRETTY_PRINT);
echo $json_pretty;

Dit geeft het volgende weer:

{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
}

Antwoord 5, autoriteit 3%

Ik had hetzelfde probleem.

Hoe dan ook, ik heb hier zojuist de json-opmaakcode gebruikt:

http://recursive-design.com /blog/2008/03/11/format-json-with-php/

Werkt goed voor waar ik het voor nodig had.

En een beter onderhouden versie: https://github.com/GerHobbelt/nicejson-php


Antwoord 6, autoriteit 3%

Het aan elkaar lijmen van verschillende antwoorden past bij mijn behoefte aan bestaande json:

Code:
echo "<pre>"; 
echo json_encode(json_decode($json_response), JSON_PRETTY_PRINT); 
echo "</pre>";
Output:
{
    "data": {
        "token_type": "bearer",
        "expires_in": 3628799,
        "scopes": "full_access",
        "created_at": 1540504324
    },
    "errors": [],
    "pagination": {},
    "token_type": "bearer",
    "expires_in": 3628799,
    "scopes": "full_access",
    "created_at": 1540504324
}

Antwoord 7, autoriteit 2%

Ik heb dit gebruikt:

echo "<pre>".json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</pre>";

Of gebruik php-headers zoals hieronder:

header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Antwoord 8

Ik heb de code overgenomen van Composer: https:/ /github.com/composer/composer/blob/master/src/Composer/Json/JsonFile.phpen nicejson: https://github.com/GerHobbelt/nicejson-php/blob/master/nicejson.php
Composer-code is goed omdat het vloeiend wordt bijgewerkt van 5.3 naar 5.4, maar het codeert alleen objecten, terwijl nicejson json-strings gebruikt, dus ik heb ze samengevoegd. De code kan worden gebruikt om json-tekenreeksen op te maken en/of objecten te coderen, ik gebruik het momenteel in een Drupal-module.

if (!defined('JSON_UNESCAPED_SLASHES'))
    define('JSON_UNESCAPED_SLASHES', 64);
if (!defined('JSON_PRETTY_PRINT'))
    define('JSON_PRETTY_PRINT', 128);
if (!defined('JSON_UNESCAPED_UNICODE'))
    define('JSON_UNESCAPED_UNICODE', 256);
function _json_encode($data, $options = 448)
{
    if (version_compare(PHP_VERSION, '5.4', '>='))
    {
        return json_encode($data, $options);
    }
    return _json_format(json_encode($data), $options);
}
function _pretty_print_json($json)
{
    return _json_format($json, JSON_PRETTY_PRINT);
}
function _json_format($json, $options = 448)
{
    $prettyPrint = (bool) ($options & JSON_PRETTY_PRINT);
    $unescapeUnicode = (bool) ($options & JSON_UNESCAPED_UNICODE);
    $unescapeSlashes = (bool) ($options & JSON_UNESCAPED_SLASHES);
    if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes)
    {
        return $json;
    }
    $result = '';
    $pos = 0;
    $strLen = strlen($json);
    $indentStr = ' ';
    $newLine = "\n";
    $outOfQuotes = true;
    $buffer = '';
    $noescape = true;
    for ($i = 0; $i < $strLen; $i++)
    {
        // Grab the next character in the string
        $char = substr($json, $i, 1);
        // Are we inside a quoted string?
        if ('"' === $char && $noescape)
        {
            $outOfQuotes = !$outOfQuotes;
        }
        if (!$outOfQuotes)
        {
            $buffer .= $char;
            $noescape = '\\' === $char ? !$noescape : true;
            continue;
        }
        elseif ('' !== $buffer)
        {
            if ($unescapeSlashes)
            {
                $buffer = str_replace('\\/', '/', $buffer);
            }
            if ($unescapeUnicode && function_exists('mb_convert_encoding'))
            {
                // http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
                $buffer = preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
                    function ($match)
                    {
                        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
                    }, $buffer);
            } 
            $result .= $buffer . $char;
            $buffer = '';
            continue;
        }
        elseif(false !== strpos(" \t\r\n", $char))
        {
            continue;
        }
        if (':' === $char)
        {
            // Add a space after the : character
            $char .= ' ';
        }
        elseif (('}' === $char || ']' === $char))
        {
            $pos--;
            $prevChar = substr($json, $i - 1, 1);
            if ('{' !== $prevChar && '[' !== $prevChar)
            {
                // If this character is the end of an element,
                // output a new line and indent the next line
                $result .= $newLine;
                for ($j = 0; $j < $pos; $j++)
                {
                    $result .= $indentStr;
                }
            }
            else
            {
                // Collapse empty {} and []
                $result = rtrim($result) . "\n\n" . $indentStr;
            }
        }
        $result .= $char;
        // If the last character was the beginning of an element,
        // output a new line and indent the next line
        if (',' === $char || '{' === $char || '[' === $char)
        {
            $result .= $newLine;
            if ('{' === $char || '[' === $char)
            {
                $pos++;
            }
            for ($j = 0; $j < $pos; $j++)
            {
                $result .= $indentStr;
            }
        }
    }
    // If buffer not empty after formating we have an unclosed quote
    if (strlen($buffer) > 0)
    {
        //json is incorrectly formatted
        $result = false;
    }
    return $result;
}

Antwoord 9

Als je Firefox gebruikt, installeer dan JSONovich. Niet echt een PHP-oplossing die ik ken, maar het doet de truc voor ontwikkelingsdoeleinden/debugging.


Antwoord 10

Eenvoudige manier voor php>5.4: zoals in Facebook-grafiek

$Data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
$json= json_encode($Data, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);

Resultaat in browser

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Antwoord 11

de beste manier om JSON-gegevens te formatteren is als volgt!

header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Vervang $respons door uw gegevens die naar JSON moeten worden geconverteerd


Antwoord 12

Kleur volledige uitvoer: kleine oplossing

Code:

$s = '{"access": {"token": {"issued_at": "2008-08-16T14:10:31.309353", "expires": "2008-08-17T14:10:31Z", "id": "MIICQgYJKoZIhvcIegeyJpc3N1ZWRfYXQiOiAi"}, "serviceCatalog": [], "user": {"username": "ajay", "roles_links": [], "id": "16452ca89", "roles": [], "name": "ajay"}}}';
$crl = 0;
$ss = false;
echo "<pre>";
for($c=0; $c<strlen($s); $c++)
{
    if ( $s[$c] == '}' || $s[$c] == ']' )
    {
        $crl--;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && ($s[$c-1] == ',' || $s[$c-2] == ',') )
    {
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && !$ss )
    {
        if ( $s[$c-1] == ':' || $s[$c-2] == ':' )
            echo '<span style="color:#0000ff;">';
        else
            echo '<span style="color:#ff0000;">';
    }
    echo $s[$c];
    if ( $s[$c] == '"' && $ss )
        echo '</span>';
    if ( $s[$c] == '"' )
          $ss = !$ss;
    if ( $s[$c] == '{' || $s[$c] == '[' )
    {
        $crl++;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
}
echo $s[$c];

Antwoord 13

Gebruik <pre>in combinatie met json_encode()en de optie JSON_PRETTY_PRINT:

<pre>
    <?php
    echo json_encode($dataArray, JSON_PRETTY_PRINT);
    ?>
</pre>

Antwoord 14

Als je een bestaande JSON hebt ($ugly_json)

echo nl2br(str_replace(' ', '&nbsp;', (json_encode(json_decode($ugly_json), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))));

Antwoord 15

Je kunt het antwoord van Kendall Hopkins een beetje aanpassen in de switch-instructie om een mooie strakke en mooi ingesprongen afdruk te krijgen door een json-string in het volgende door te geven:

function prettyPrint( $json ){
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
    $char = $json[$i];
    $new_line_level = NULL;
    $post = "";
    if( $ends_line_level !== NULL ) {
        $new_line_level = $ends_line_level;
        $ends_line_level = NULL;
    }
    if ( $in_escape ) {
        $in_escape = false;
    } else if( $char === '"' ) {
        $in_quotes = !$in_quotes;
    } else if( ! $in_quotes ) {
        switch( $char ) {
            case '}': case ']':
                $level--;
                $ends_line_level = NULL;
                $new_line_level = $level;
                $char.="<br>";
                for($index=0;$index<$level-1;$index++){$char.="-----";}
                break;
            case '{': case '[':
                $level++;
                $char.="<br>";
                for($index=0;$index<$level;$index++){$char.="-----";}
                break;
            case ',':
                $ends_line_level = $level;
                $char.="<br>";
                for($index=0;$index<$level;$index++){$char.="-----";}
                break;
            case ':':
                $post = " ";
                break;
            case "\t": case "\n": case "\r":
                $char = "";
                $ends_line_level = $new_line_level;
                $new_line_level = NULL;
                break;
        }
    } else if ( $char === '\\' ) {
        $in_escape = true;
    }
    if( $new_line_level !== NULL ) {
        $result .= "\n".str_repeat( "\t", $new_line_level );
    }
    $result .= $char.$post;
}
echo "RESULTS ARE: <br><br>$result";
return $result;

}

Voer nu gewoon de functie PrettyPrint ($ your_json_string) uit; inline in uw PHP en geniet van de afdruk. Als je een minimalistisch bent en niet houdt van haakjes om de een of andere reden, kun je die gemakkelijk kwijt raken door de $char.="<br>";met $char="<br>";in de top drie schakelaars op $ Char. Dit is wat u krijgt voor een Google Maps API CALL voor de City of Calgary

RESULTS ARE: 
{
- - - "results" : [
- - -- - - {
- - -- - -- - - "address_components" : [
- - -- - -- - -- - - {
- - -- - -- - -- - -- - - "long_name" : "Calgary"
- - -- - -- - -- - -- - - "short_name" : "Calgary"
- - -- - -- - -- - -- - - "types" : [
- - -- - -- - -- - -- - -- - - "locality"
- - -- - -- - -- - -- - -- - - "political" ]
- - -- - -- - -- - - }
- - -- - -- - -
- - -- - -- - -- - - {
- - -- - -- - -- - -- - - "long_name" : "Division No. 6"
- - -- - -- - -- - -- - - "short_name" : "Division No. 6"
- - -- - -- - -- - -- - - "types" : [
- - -- - -- - -- - -- - -- - - "administrative_area_level_2"
- - -- - -- - -- - -- - -- - - "political" ]
- - -- - -- - -- - - }
- - -- - -- - -
- - -- - -- - -- - - {
- - -- - -- - -- - -- - - "long_name" : "Alberta"
- - -- - -- - -- - -- - - "short_name" : "AB"
- - -- - -- - -- - -- - - "types" : [
- - -- - -- - -- - -- - -- - - "administrative_area_level_1"
- - -- - -- - -- - -- - -- - - "political" ]
- - -- - -- - -- - - }
- - -- - -- - -
- - -- - -- - -- - - {
- - -- - -- - -- - -- - - "long_name" : "Canada"
- - -- - -- - -- - -- - - "short_name" : "CA"
- - -- - -- - -- - -- - - "types" : [
- - -- - -- - -- - -- - -- - - "country"
- - -- - -- - -- - -- - -- - - "political" ]
- - -- - -- - -- - - }
- - -- - -- - - ]
- - -- - -
- - -- - -- - - "formatted_address" : "Calgary, AB, Canada"
- - -- - -- - - "geometry" : {
- - -- - -- - -- - - "bounds" : {
- - -- - -- - -- - -- - - "northeast" : {
- - -- - -- - -- - -- - -- - - "lat" : 51.18383
- - -- - -- - -- - -- - -- - - "lng" : -113.8769511 }
- - -- - -- - -- - -
- - -- - -- - -- - -- - - "southwest" : {
- - -- - -- - -- - -- - -- - - "lat" : 50.84240399999999
- - -- - -- - -- - -- - -- - - "lng" : -114.27136 }
- - -- - -- - -- - - }
- - -- - -- - -
- - -- - -- - -- - - "location" : {
- - -- - -- - -- - -- - - "lat" : 51.0486151
- - -- - -- - -- - -- - - "lng" : -114.0708459 }
- - -- - -- - -
- - -- - -- - -- - - "location_type" : "APPROXIMATE"
- - -- - -- - -- - - "viewport" : {
- - -- - -- - -- - -- - - "northeast" : {
- - -- - -- - -- - -- - -- - - "lat" : 51.18383
- - -- - -- - -- - -- - -- - - "lng" : -113.8769511 }
- - -- - -- - -- - -
- - -- - -- - -- - -- - - "southwest" : {
- - -- - -- - -- - -- - -- - - "lat" : 50.84240399999999
- - -- - -- - -- - -- - -- - - "lng" : -114.27136 }
- - -- - -- - -- - - }
- - -- - -- - - }
- - -- - -
- - -- - -- - - "place_id" : "ChIJ1T-EnwNwcVMROrZStrE7bSY"
- - -- - -- - - "types" : [
- - -- - -- - -- - - "locality"
- - -- - -- - -- - - "political" ]
- - -- - - }
- - - ]
- - - "status" : "OK" }

Antwoord 16

Voor degenen die PHP versie 5.3 of eerder gebruiken, kunt u het hieronder proberen:

$pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";
echo $pretty_json;

Antwoord 17

Als je alleen $json_string = json_encode($data, JSON_PRETTY_PRINT);hebt gebruikt, krijg je zoiets als dit in de browser (met behulp van de Facebook-linkvan de vraag 🙂 ):

maarals je een Chrome-extensie zoals JSONView(zelfs zonder de bovenstaande PHP-optie), dan krijg je een mooi leesbare debuggable oplossingwaar je zelfs elk afzonderlijk JSON-object gemakkelijk als volgt kunt vouwen/samenvouwen:


Antwoord 18

Je zou het zoals hieronder kunnen doen.

$array = array(
   "a" => "apple",
   "b" => "banana",
   "c" => "catnip"
);
foreach ($array as $a_key => $a_val) {
   $json .= "\"{$a_key}\" : \"{$a_val}\",\n";
}
header('Content-Type: application/json');
echo "{\n"  .rtrim($json, ",\n") . "\n}";

Bovenstaande zou een soort van als Facebook weergeven.

{
"a" : "apple",
"b" : "banana",
"c" : "catnip"
}

Antwoord 19

Klassiek geval voor een recursieve oplossing. Dit is de mijne:

class JsonFormatter {
    public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
        $inString = $escaped = false;
        $result = $indent;
        if(is_string($j)) {
            $bak = $j;
            $j = str_split(trim($j, '"'));
        }
        while(count($j)) {
            $c = array_shift($j);
            if(false !== strpos("{[,]}", $c)) {
                if($inString) {
                    $result .= $c;
                } else if($c == '{' || $c == '[') {
                    $result .= $c."\n";
                    $result .= self::prettyPrint($j, $indentor, $indentor.$indent);
                    $result .= $indent.array_shift($j);
                } else if($c == '}' || $c == ']') {
                    array_unshift($j, $c);
                    $result .= "\n";
                    return $result;
                } else {
                    $result .= $c."\n".$indent;
                } 
            } else {
                $result .= $c;
                $c == '"' && !$escaped && $inString = !$inString;
                $escaped = $c == '\\' ? !$escaped : false;
            }
        }
        $j = $bak;
        return $result;
    }
}

Gebruik:

php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
    [foo] => 1
    [bar] => This "is" bar
    [baz] => Array
        (
            [a] => 1
            [b] => 2
            [c] => "3"
        )
)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
    "foo":1,
    "bar":"This \"is\" bar",
    "baz":{
        "a":1,
        "b":2,
        "c":"\"3\""
    }
}

Proost


Antwoord 20

Deze oplossing maakt ‘echt mooie’ JSON. Niet precies waar de OP om vroeg, maar het laat je de JSON beter visualiseren.

/**
 * takes an object parameter and returns the pretty json format.
 * this is a space saving version that uses 2 spaces instead of the regular 4
 *
 * @param $in
 *
 * @return string
 */
function pretty_json ($in): string
{
  return preg_replace_callback('/^ +/m',
    function (array $matches): string
    {
      return str_repeat(' ', strlen($matches[0]) / 2);
    }, json_encode($in, JSON_PRETTY_PRINT | JSON_HEX_APOS)
  );
}
/**
 * takes a JSON string an adds colours to the keys/values
 * if the string is not JSON then it is returned unaltered.
 *
 * @param string $in
 *
 * @return string
 */
function markup_json (string $in): string
{
  $string  = 'green';
  $number  = 'darkorange';
  $null    = 'magenta';
  $key     = 'red';
  $pattern = '/("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/';
  return preg_replace_callback($pattern,
      function (array $matches) use ($string, $number, $null, $key): string
      {
        $match  = $matches[0];
        $colour = $number;
        if (preg_match('/^"/', $match))
        {
          $colour = preg_match('/:$/', $match)
            ? $key
            : $string;
        }
        elseif ($match === 'null')
        {
          $colour = $null;
        }
        return "<span style='color:{$colour}'>{$match}</span>";
      }, str_replace(['<', '>', '&'], ['&lt;', '&gt;', '&amp;'], $in)
   ) ?? $in;
}
public function test_pretty_json_object ()
{
  $ob       = new \stdClass();
  $ob->test = 'unit-tester';
  $json     = pretty_json($ob);
  $expected = <<<JSON
{
  "test": "unit-tester"
}
JSON;
  $this->assertEquals($expected, $json);
}
public function test_pretty_json_str ()
{
  $ob   = 'unit-tester';
  $json = pretty_json($ob);
  $this->assertEquals("\"$ob\"", $json);
}
public function test_markup_json ()
{
  $json = <<<JSON
[{"name":"abc","id":123,"warnings":[],"errors":null},{"name":"abc"}]
JSON;
  $expected = <<<STR
[
  {
    <span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>,
    <span style='color:red'>"id":</span> <span style='color:darkorange'>123</span>,
    <span style='color:red'>"warnings":</span> [],
    <span style='color:red'>"errors":</span> <span style='color:magenta'>null</span>
  },
  {
    <span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>
  }
]
STR;
  $output = markup_json(pretty_json(json_decode($json)));
  $this->assertEquals($expected,$output);
}

}


Antwoord 21

print_r mooie print voor PHP

Voorbeeld PHP

function print_nice($elem,$max_level=10,$print_nice_stack=array()){
    if(is_array($elem) || is_object($elem)){
        if(in_array($elem,$print_nice_stack,true)){
            echo "<font color=red>RECURSION</font>";
            return;
        }
        $print_nice_stack[]=&$elem;
        if($max_level<1){
            echo "<font color=red>nivel maximo alcanzado</font>";
            return;
        }
        $max_level--;
        echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
        if(is_array($elem)){
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
        }else{
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
            echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
        }
        $color=0;
        foreach($elem as $k => $v){
            if($max_level%2){
                $rgb=($color++%2)?"#888888":"#BBBBBB";
            }else{
                $rgb=($color++%2)?"#8888BB":"#BBBBFF";
            }
            echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
            echo '<strong>'.$k."</strong></td><td>";
            print_nice($v,$max_level,$print_nice_stack);
            echo "</td></tr>";
        }
        echo "</table>";
        return;
    }
    if($elem === null){
        echo "<font color=green>NULL</font>";
    }elseif($elem === 0){
        echo "0";
    }elseif($elem === true){
        echo "<font color=green>TRUE</font>";
    }elseif($elem === false){
        echo "<font color=green>FALSE</font>";
    }elseif($elem === ""){
        echo "<font color=green>EMPTY STRING</font>";
    }else{
        echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
    }
}

Antwoord 22

1 – json_encode($rows,JSON_PRETTY_PRINT);retourneert verbeterde gegevens met nieuwe regeltekens. Dit is handig voor invoer via de opdrachtregel, maar zoals je hebt ontdekt, ziet het er niet zo mooi uit in de browser. De browser accepteert de nieuwe regels als de bron (en dus zal het bekijken van de paginabron inderdaad de mooie JSON tonen), maar ze worden niet gebruikt om de uitvoer in browsers te formatteren. Browsers hebben HTML nodig.

2 – gebruik deze functie 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;&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 '[':
                    case '{':
                        $tabcount++;
                        $result .= $char . $newline . str_repeat($tab, $tabcount);
                        break;
                    case ']':
                    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;
    }

Antwoord 23

Het volgende is wat voor mij werkte:

Inhoud van test.php:

<html>
<body>
Testing JSON array output
  <pre>
  <?php
  $data = array('a'=>'apple', 'b'=>'banana', 'c'=>'catnip');
  // encode in json format 
  $data = json_encode($data);
  // json as single line
  echo "</br>Json as single line </br>";
  echo $data;
  // json as an array, formatted nicely
  echo "</br>Json as multiline array </br>";
  print_r(json_decode($data, true));
  ?>
  </pre>
</body>
</html>

Uitgang:

Testing JSON array output
Json as single line 
{"a":"apple","b":"banana","c":"catnip"}
Json as multiline array 
Array
(
    [a] => apple
    [b] => banana
    [c] => catnip
)

Let ook op het gebruik van “PRE” -tag in HTML.

Hoop dat iemand iemand helpt


Antwoord 24

hier is de functie die ik zelf gebruik, de api is net als json_encode, behalve dat het een derde argument heeft exclude_flagsvoor het geval je enkele van de standaardvlaggen wilt uitsluiten (zoals JSON_UNESCAPED_SLASHES)

function json_encode_pretty($data, int $extra_flags = 0, int $exclude_flags = 0): string
{
    // prettiest flags for: 7.3.9
    $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_PRESERVE_ZERO_FRACTION | (defined("JSON_THROW_ON_ERROR") ? JSON_THROW_ON_ERROR : 0);
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;
    return (json_encode($data, $flags));
}

Antwoord 25

json_encode($json,128);
//OR
json_encode($json,JSON_PRETTY_PRINT );

Antwoord 26

Als u werkt met MVC

probeer dit in je controller

public function getLatestUsers() {
    header('Content-Type: application/json');
    echo $this->model->getLatestUsers(); // this returns json_encode($somedata, JSON_PRETTY_PRINT)
}

als je /getLatestUsers aanroept, krijg je een mooie JSON-uitvoer 😉

Other episodes