Last active
July 24, 2023 07:23
-
-
Save tluyben/b5e0121ff8e65767d566e34ee3f82c84 to your computer and use it in GitHub Desktop.
A php json encode that doesn't care about encoding.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _json_encode($ar) { | |
$res = ""; | |
if (is_array($ar)) { | |
if (count($ar)==0) { | |
return $res; | |
} | |
if (is_numeric(array_keys($ar)[0])) { | |
$res .= "\n[\n"; | |
for($i=0;$i<count($ar);$i++) { | |
$v = $ar[$i]; | |
$res .= _json_encode($v); | |
if ($i<count($ar)-1) $res.=",\n"; | |
} | |
$res .= "\n]\n"; | |
} else { | |
$res .= "\n{\n"; | |
$keys = array_keys($ar); | |
for($i=0;$i<count($keys);$i++) { | |
$k = $keys[$i]; | |
$v = $ar[$k]; | |
$res .= '"'.$k.'"'.":"._json_encode($v); | |
if ($i<count($keys)-1) $res.=",\n"; | |
} | |
$res .="\n}\n"; | |
} | |
} else if (is_object($ar)) { | |
$res .= "\n{\n"; | |
$keys = array_keys((array)$ar); | |
for($i=0;$i<count($keys);$i++) { | |
$k = $keys[$i]; | |
$v = $ar[$k]; | |
$res .= '"'.$k.'"'.":"._json_encode($v); | |
if ($i<count($keys)-1) $res.=",\n"; | |
} | |
$res .="\n}\n"; | |
} else { | |
$ar = str_replace('"','\"',$ar); | |
$ar = str_replace("\n", '\\n', $ar); | |
$res .= '"'.$ar.'"'; | |
} | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment