note 95461 deleted from function.json-encode by danbrown
| From: | danbrown@php.net | Date: | Mon, 04 Jan 2010 16:07:32 +0000 |
| Subject: | note 95461 deleted from function.json-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164623@lists.php.net to get a copy of this message | ||
Note Submitter: rene
----
just finished a raw hack that lets you embed json within json, or html or javascript within json,
and publish it all in a javascript data object.
i use it to dump complex arrays to html,
with json->html done in js because that allows me to print any js vars the same as any php vars.
here's a very basic setup (lgpl-ed), no actual 'collapsiblity of sub-items' yet;
<?php
function htmlDump ($var, $title) {
echo htmlDumpReturn ($var, $title);
}
function htmlDumpReturn ($var, $title) {
$id = preg_replace('/\s/','',getDuration());
$id = preg_replace('/\./','_', $id);
$htmlID = 'debug_'.$id;
$data = json_encode4(json_prepare($var));
$r = '';
$r.= '<div id="'.$htmlID.'"> </div>';
$r.= '<script type="text/javascript" language="javascript">';
$r.= '<!-- '."\n";
$r.= 'var debugData = {';
$r.= ' "data" : "'.$data.'",';
$r.= ' "title" : "'.$title.'", ';
$r.= ' "id" : "'.$htmlID.'" ';
$r.= '};'."\n";
$r.= 'debugPrintCollapsible (debugData); '."\n";
$r.= '-->'."\n";
$r.= '</script>';
return $r;
}
function json_prepare ($v) {
if (is_array($v)) {
foreach ($v as $k=>$w) {
$v[$k] = json_prepare($w);
}
} elseif (is_string($v)) {
$v = preg_replace('/([^\\\\])"/', '$1\\"', $v);
$v = preg_replace('/([^\\\\])::/', '$1\\:\\:', $v);
$v = preg_replace('/([^\\\\]):/', '$1\\:', $v);
$v = preg_replace('/}/', '\\}', $v);
$v = preg_replace('/\]/', '\\]', $v);
$v = preg_replace('/{/', '\\{', $v);
$v = preg_replace('/\[/', '\\[', $v);
$v = preg_replace('/\s\s+/', ' ', $v);
$v = preg_replace('/[\n\r]/', '', $v);
} elseif (is_resource($v)) {
$v = '[php resource '.get_resource_type($v).']';
}
return $v;
}
function json_encode_safe($a)
//was formerly php_js() by php at koterov dot ru, slightly modified by rene
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a)) {
$a = addslashes($a);
$a = str_replace("\n", '\n', $a);
$a = str_replace("\r", '\r', $a);
$a = preg_replace('{(</)(script)}i', "$1'+'$2", $a);
//return "'$a'";
return '\"'.$a.'\"';
}
$isList = true;
for ($i=0, reset($a); $i<count($a); $i++, next($a))
if (key($a) !== $i) { $isList = false; break; }
$result = array();
if ($isList) {
foreach ($a as $v) $result[] = json_encode_safe($v);
return '[ ' . join(', ', $result) . ' ]';
} else {
foreach ($a as $k=>$v)
$result[] = json_encode_safe($k) . ': ' . json_encode_safe($v);
return '{ ' . join(', ', $result) . ' }';
}
}
?>