Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email:


PHP array to JSON in CakePHP

It is an often asked question on the CakePHP google groups, how to pass a php array to javascript. The answer is to convert the PHP array to JSON, I have seen several solutions recommended which included using vendor classes, the PHP 5 extension for JSON – however the recommended way is to use the ‘Object’ method of javascript helper. Being a pure PHP solution it works in both PHP 4 as well 5

Using it is as simple as using any other helper, suppose you have some arrays in your controller, just pass them to the view and use.

OK! here is stripped down code snippet with output

Controller code

View code

The output is

A more complex output from the result of findAll in Cheesecake-Photoblog is shown below.

Resultant JSON

What you now do with the JSON output is entirely upto you

About the Author

Dr. Tarique Sani is a pediatrician and forensic expert by education. He is a PHP programmer of 'wrote the book' caliber and has to his credit several very popular open source as well as commercial PHP projects. He leads a team of dynamic programmers at SANIsoft who have in-depth understanding of Web scalability, development tools and usability practices with strong developmental skills in PHP, MySQL/PostgreSQL, HTML, Javascript, and Linux/Apache