I'm using this code to encode large(cca 60mb) geojson before storing it to database:
// controller
public function importZones () {
ini_set('max_execution_time', '0');
ini_set('memory_limit', '-1');
ini_set("precision", -1);
ini_set("serialize_precision", -1);
$this->load->helper('url');
$filePath = base_url('assets/zones/zone.geojson');
$jsonStream = \JsonMachine\JsonMachine::fromFile($filePath, "/features");
$this->PolygonModel->import($jsonStream)
}
// model
public function import ($jsonStream) {
$import = [];
foreach ($jsonStream as $name => $data) {
// $coordinates is nested indexed array with possibly thousands of elements
$coordinates = json_encode($data['geometry']['coordinates']);
$import['baz'][] = [
'foo' => 'bar',
'coordinates' => $coordinates
];
}
echo json_last_error_msg(); // gives no errors
// insert encoded data to db...
}
I'm using this code to decode the string after selecting it from database
// decode and fix json if corrupted (huge arrays..)
private function decodeZoneCoords ($coordsJson) {
$decoded = json_decode($coordsJson, true);
if (!$decoded) {
// some fixes I've found online
$json = $coordsJson;
// before removing cntrl I get the “Control character error, possibly incorrectly encoded” error
$json = preg_replace('/[[:cntrl:]]/', '', $coordsJson);
$json = preg_replace('/[[:^print:]]/', '', $coordsJson);
$json = mb_convert_encoding($json, "UTF-8");
$json = ltrim($json . '"' . "]", '1');
if (0 === strpos(bin2hex($json), 'efbbbf')) {
$json = substr($json, 3);
}
$decoded = json_decode($json, true);
if (!$decoded) {
$json = rtrim($json, ',"]') . '"]';
$decoded = json_decode($json, true);
}
}
if (!$decoded) {
echo "<pre>";
var_dump( json_decode($json, true) ); // null
echo "</pre>";
echo json_last_error_msg(); // "syntax error"
echo 'JSON ERROR(from zone):';
echo '<hr>';
echo $json;
die();
}
return $decoded;
}
When I try to decode it I get syntax error message from json_last_error_msg function and json_encode function returns null.
Edit:
I just realized that var_dumping the string gives me this: string(65535) "...
Could it be that MySql truncates my JSON after that lenght even though im using the text field to store encoded string?
text,mediumtextorlongtextyou should be using JSON for the data type