This took me a few minutes today to work out and find an answer on Google so I thought I’d share it.

I had a string that I was posting from a form and while Firebug on the client said that the string was valid, on the server side PHP’s json_decode() function was returning me a NULL indicating invalid JSON. I spit out the string using good old var_dump() and I could see straight away that I would need to strip some slashes from it, but I couldn’t figure out why.

I don’t like to simply know how to fix something, I like to know why it was broken in the first place! A bit of Googling gave me the answer, it turned out to be because of the magic_quotes setting in PHP.

Instead of just wrapping everything in a stripslashes() call I decided to write a wrapper function that will take into account whether magic_quotes is on or off. It will also allow me to do whatever I want later one if I wanted to parse a particular type of data or something.

Here is the code. As you can see it’s nothing fancy, but it works and hopefully it saves people some time.

function _json_decode($string) {
	if (get_magic_quotes_gpc()) {
		$string = stripslashes($string);
	}

	return json_decode($string);
}

Posted in Code, Tips and Tricks at November 7th, 2008. Trackback URI: trackback
Tags: , ,

6 Responses to “json_decode() Not Working in PHP?”

  1. December 31st, 2008 at 1:04 pm #Declan

    Excellent - this has saved me some time. I was having trouble working out why a json_encoded object could not then be immediately json_decoded.

  2. February 4th, 2009 at 12:30 am #Manny Calavera

    You are the MAN! I’ve spent a lot of time trying to figure out why json_decode was working great on my local server but once moved to my webserver it kept coming out NULL.

    Thank you!

  3. February 10th, 2009 at 3:35 pm #Miklós Kriván

    Thanks for this simple but excellent help :-)
    I had big headache this night. But now it works again :-)

    God bless you!

  4. February 20th, 2009 at 7:42 am #Henrik Petersson

    Magic quotes are evil, can’t imagine why anyone would leave it on by default.

    Thanks for the info. I switched PHP distribution (to entropy) for my local server and couldn’t figure out why json_encode stopped working. Turned out magic quotes was turned on. *shudders*

  5. February 23rd, 2009 at 9:30 pm #JM

    Muchas gracias amigo !

  6. March 19th, 2009 at 12:26 am #tim

    Thank you a lot, this fixed my site!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>