If you're trying to detect valid json then atleat make sure the "param" you pass to json_decode is of type string.
Quote from php.net:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null (case-insensitive) are returned as TRUE, FALSE
and NULL respectively. NULL is returned if the json cannot be decoded
or if the encoded data is deeper than the recursion limit.
So it's NULL that we're looking for if the JSON cannot be decoded. Thus, invalid JSON. But again, just make sure you pass in a string and not some other type, like an array or boolean or something. Because that will never work.
And i understand your problem. The @ sign suppresses the error message, but not the actual code flow. It still exits when it goes wrong. But you really just have to let go of the @ sign.
So anyway, you'd probably have some sort of function that you call which does some stuff including the json_decode. This is just an example, but it should give you an idea of what i mean.
<?php
// will fail, because it's not a string
$str1 = array ( "nooblol" );
// Will succeed. This is valid json
$str2 = '{"example":"value"}';
// Will fail, is of type string, but still an invalid json format
$str3 = 'invalid json string';
function saveData ( $json )
{
// Check if the variable that we're about to pass
// to json_decode() is an actual string. Otherwise we
// have invalid json data anyway.
if ( !is_string ( $json ) )
{
echo 'Invalid json (or invalid type)';
return;
}
if ( !$obj = json_decode ( $json ) )
{
echo 'fail';
return;
}
// Print json object
print_r($obj);
}
saveData ( $str3 );
?>
Live example: http://codepad.viper-7.com/KJL8st
Change the saveData param to $str1 or $str2 to see the different results.
This is the way to check if you have valid json. Don't solely depend on the json_decode() function to tell you wether it's valid data or not. it's a function and it simply expects a string. So make sure you pass in a string. Only then it can tell you wether it's valid json or not.
arrayto thejson_decodefunction instead of a string. No wonder it spits out an error. Just make sure the $variable is actually of type string. -2 for you :-)@too in detecting valid json data. The topic is very much related. BTW I am the OP. -2 for you :-)