note 129248 added to function.json-validate

From: Date: Thu, 15 Feb 2024 05:26:23 +0000
Subject: note 129248 added to function.json-validate
Groups: php.notes 
Request: Send a blank email to php-notes+get-221200@lists.php.net to get a copy of this message
Building upon Allan R.'s initial idea, I've developed an improved version of the json_validate function for those using PHP 8.2 and earlier versions. This function emulates the functionality introduced in PHP 8.3, providing an effective way to validate JSON strings in earlier PHP versions. ```php if (!function_exists('json_validate')) { /** * Validates a JSON string. * * @param string $json The JSON string to validate. * @param int $depth Maximum depth. Must be greater than zero. * @param int $flags Bitmask of JSON decode options. * @return bool Returns true if the string is a valid JSON, otherwise false. */ function json_validate($json, $depth = 512, $flags = 0) { if (!is_string($json)) { return false; } try { json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR); return true; } catch (\JsonException $e) { return false; } } } ``` Key Improvements: - String Check: Added a validation to ensure the input is a string. - Error Handling: Utilizes try-catch to effectively catch and handle JsonException. - Backward Compatibility: Safely integrable in older PHP versions, automatically deferring to native functionality in PHP 8.3+. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.131 (proxied: 173.246.6.19) ---- Manual Page -- https://php.net/manual/en/function.json-validate.php Edit -- https://main.php.net/note/edit/129248 Del: integrated -- https://main.php.net/note/delete/129248/integrated Del: useless -- https://main.php.net/note/delete/129248/useless Del: bad code -- https://main.php.net/note/delete/129248/bad+code Del: spam -- https://main.php.net/note/delete/129248/spam Del: non-english -- https://main.php.net/note/delete/129248/non-english Del: in docs -- https://main.php.net/note/delete/129248/in+docs Del: other reasons-- https://main.php.net/note/delete/129248 Reject -- https://main.php.net/note/reject/129248 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221200) next »