I have some json_encode related issues : i need to use a big array (several 100k items), each with very simple structure (one key, one string value). json_decode works ok, but as soon as i want to json_encode it, it's awfully slow. Since i fully control the data here, i tried to write a super simple json encoder, and it's fast. I'm quite surprised, since my encoding function is crude, and oes not have any of the inner php optimizations that are quite certainly present in json_encode.
Any idea what the problem might be ?
I put my encoder function below for reference.
Thanks
protected function simpleJsonEncoder($data) {
if (is_array($data)) {
$is_indexed = (array_values($data) === $data);
$tab_str = [];
if ($is_indexed) {
foreach($data as $item) {
$str_item = $this->simpleJsonEncoder($item);
$tab_str[] = $str_item;
}
$result = '[' . implode(',', $tab_str) . ']';
}
else {
foreach($data as $index => $item) {
$str_item = $this->simpleJsonEncoder($item);
$tab_str[] = '"' . htmlspecialchars($index, ENT_QUOTES) . '":' . $str_item;
}
$result = '{' . implode(',', $tab_str) . '}';
}
}
else {
$result = '"' . htmlspecialchars($data, ENT_QUOTES) . '"';
}
return $result;
}