$product) { if (is_array($product) && !array_key_exists("category_id", $product)) { $data[$index]["category_id"] = null; $changed = true; } } if (!$changed) { return; } $json = json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, ); if ($json === false) { throw new RuntimeException("products.json could not be encoded."); } // Write atomically, so an interruption never leaves a half-written file. $tmpFile = $file . ".tmp"; if (file_put_contents($tmpFile, $json, LOCK_EX) === false || !rename($tmpFile, $file)) { @unlink($tmpFile); throw new RuntimeException("products.json could not be written."); } };