ruhul080
ruhul080

Reputation: 45

php json_decode() giving null

I have a json string like below

{"cv_url":"http://localhost/kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc","cv_path":"C:\wamp\www\kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc"}

while trying to decode by php json_decode() it giving me null value.

Any help is appreciated.

Thanks

Upvotes: 1

Views: 139

Answers (1)

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

That is because your JSON in invalid. You need to escape it like so:

{
    "cv_url": "http://localhost/kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc",
    "cv_path": "C:\\wamp\\www\\kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc"
}

So your variable should actually be:

'{"cv_url": "http://localhost/kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc","cv_path": "C:\\wamp\\www\\kaj/wp-content/uploads/2017/03/Mir-Ruhul-Amin.doc"}'

for PHP to decode it.

To escape JSON you can simply encode the array in php first or if that does not suit you you can use the following function:

/**
 * @param $value
 * @return mixed
 */
function escapeJsonString($value) {
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}

TIP:

You can always test the validity of your json on online tools like:

http://jsonlint.com

and

http://www.jsoneditoronline.org/

Upvotes: 2

Related Questions