note 98040 deleted from function.json-encode by derick

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
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"
        ]
}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.