When you have first installed PHP, you may find that json_decode
doesn't work. What will happen is you will be given no output at all. Carry on reading if you would like to know how to fix it.
To determine the symptoms:
- Enable error messages to be shown by writing
ini_set('display_errors', '1');
in your PHP code. - Most likely, you will be given this error message now:
Php Fatal Error Call To Undefined Function Json_decode
The solution:
- Open your
php.ini
file (eg.nano /etc/php/php.ini
depending on distro) - In the configuration file there will be a section called
Dynamic Extensions
. You will find a list of extensions which have been conveniently commented out to improve PHP performance. - Uncomment the line
;extension=json.so
by removing the semi-colon - Save the configuration file and restart Apache (eg. /etc/rc.d/httpd restart depending on your distro)
Hopefully this will save you having to bang your head against a wall when you can't parse even the most simplest of JSON.
For good measure, you may well want to try this example from the php.net website:
var_dump(json_decode($json));
var_dump(json_decode($json, true));
??>
Assuming you've fixed the problem, this should output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
This was my first blog post for this site, so I feel an introduction is in order.
My name is Nick Hatter and I am currently studying MEng Computer Science at the School of Electronics and Computer Science (ECS) in Southampton University. I decided it was time to do my first blog post seeing as I keep running into 'gotcha!'s and I feel I would save everyone a lot of hassle if I shared some of my solutions!
Hi Nick,
Nice article. I ran into this problem the other day but for a slightly different reason. A lot of web hosts run RHEL 5 or CentOS 5, which include the fairly out-of-date PHP 5.1.6. The function
json_decode()
was added to PHP in 5.2.0, so if you need to use it in a web app that's hosted on one of these platforms you will run into problems.Luckily there is still a workaround, you can just add in an external file that defines the function if it's missing. See http://web.archive.org/web/20090429084654/http://forums.mawhorter.net/v…, I tried it and it works a treat on PHP 5.1.6 while still maintaining compatibility with PHP 5.2.0+.