Skip to content

Instantly share code, notes, and snippets.

@attitude
Last active December 19, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attitude/5984199 to your computer and use it in GitHub Desktop.
Save attitude/5984199 to your computer and use it in GitHub Desktop.
Decodes JSON string if needed
<?php
/**
* Decodes JSON string if needed
*
* @uses json_decode()
* @author Martin Adamko <@martin_adamko>
* @licence The MIT Licence <http://opensource.org/licenses/MIT>
*
* @param string $str String to decode if needed
* @param bool $assoc When TRUE, returned objects will be converted into associative arrays
* @param int $depth User specified recursion depth
* @param int $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)
* @returns mixed
*
*/
function maybe_decode_json($str, $assoc = false, $depth = 512, $options = 0)
{
if (!is_string($str)) {
return $str;
}
// Trim it
$str = trim($str);
// Nothing to do with an empty string
if (strlen($str)===0) {
return '';
}
// Any "null" string would return NULL (decoding error returns also NULL)
if ($str==='null') {
return null;
}
// Decode it
$data = json_decode($str, $assoc, $depth, $options);
// Decoding error
if ($data===null) {
return $str;
}
// Success
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment