note 98040 deleted from function.json-encode by derick
| From: | derick@php.net | Date: | Fri, 28 May 2010 16:31:31 +0000 |
| Subject: | note 98040 deleted from function.json-encode by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-169695@lists.php.net to get a copy of this message | ||
Note Submitter: spansjh at nospam dot gmail dot com
----
The function json_encode does not return the JSON code in 'human-readable' formats. The
function below will format any JSON code given to it.
<?php
function json_format($input){
$tab = 0;
$out = "";
$tabs = "";
for($i=0;$i<strlen($input);$i++){
$c = $input[$i];
$tabs = "";
for($t=1;$t<=$tab;$t++)
$tabs .= "\t";
switch($c){
case "{":
$tab++;
$tabs .= "\t";
$out .= "{\n".$tabs;
break;
case "}":
$tab--;
$tabs[strlen($tabs)-1] = "";
$out .= "\n".$tabs."}";
break;
case "[":
$tab++;
$tabs .= "\t";
$out .= "[\n".$tabs;
break;
case "]":
$tab--;
$tabs[strlen($tabs)-1] = "";
$out .= "\n".$tabs."]";
break;
case ",": $out .= ",\n".$tabs; break;
default: $out .= $c; break;
}
}
$out = str_replace("\x00", "", $out);
return $out;
}
?>
Example:
<?php
$a = array("Name"=>"Angelo","Age"=>16,
"Interests"=>array("Games","Television","Holidays"));
echo json_format(json_encode($a));
?>
This will output:
{
"Name":"Angelo",
"Age":16,
"Interests":[
"Games",
"Television",
"Holidays"
]
}