1

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

4
  • how do you get this json ? you encodeing it your self or get it via api for example ? Commented Mar 21, 2017 at 10:14
  • I get it by json_encode() function Commented Mar 21, 2017 at 10:47
  • how do you encode your array ? Commented Mar 21, 2017 at 11:01
  • checkout this: 3v4l.org/mnP6o seems that there are no problem in both encoding and decoding Commented Mar 21, 2017 at 11:02

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

and how he could escape it ? put a full solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.