json_decode returns JSON_ERROR_SYNTAX in OpenCart
Seems OpenCart (or somthing else) was changing the "
(quotes) to "
, therby breaking the JSON.
I added the following line befor I decode the JSON, this fixed the issue.
$rules = str_replace('"', '"', $rules);
PHP json_decode() returns NULL with valid JSON?
It could be the encoding of the special characters. You could ask json_last_error() to get definite information.
Update: The issue is solved, look at the "Solution" paragraph in the question.
Detect bad json data in PHP json_decode()?
Here are a couple of things about json_decode
:
- it returns the data, or
null
when there is an error - it can also return
null
when there is no error : when the JSON string containsnull
- it raises a warning where there is a warning -- warning that you want to make disappear.
To solve the warning problem, a solution would be to use the @
operator (I don't often recommend using it, as it makes debuging a lot more harder... But here, there is not much of a choice) :
$_POST = array(
'bad data'
);
$data = @json_decode($_POST);
You'd then have to test if $data
is null
-- and, to avoid the case in which json_decode
returns null
for null
in the JSON string, you could check json_last_error
, which (quoting) :
Returns the last error (if any)
occurred by last JSON parsing.
Which means you'd have to use some code like the following :
if ($data === null
&& json_last_error() !== JSON_ERROR_NONE) {
echo "incorrect data";
}
json_decode returns NULL after webservice call
EDIT:
Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF
. I don't know why this byte sequence is displayed as
here.
Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode()
(a substr($string, 3)
will do).
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
^
|
This is the UTF-8 BOM
As Kuroki Kaze discovered, this character surely is the reason why json_decode
fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)
Related Topics
Login Without Https, How to Secure
Download Files in Laravel Using Response::Download
Convert Latin1 Characters on a Utf8 Table into Utf8
PHP Expression ≪≪≪Eob
How to Re-Index the Values of an Array in PHP
Laravel 5 Failed Opening Required Bootstrap/../Vendor/Autoload.PHP
Passing an Array as Arguments, Not an Array, in PHP
Checking to See If One Array'S Elements Are in Another Array in PHP
Rebase Array Keys After Unsetting Elements
How to Execute PHP That Is Stored in a MySQL Database