how to convert Doctrine object into json

cc96ai picture cc96ai · Dec 20, 2009 · Viewed 31k times · Source

I am using Doctrine 1.2, how could I get the query object into json / array format?

$user = Doctrine_Query::create()
->select('u.id, u.username, u.firstname, u.lastname')
->from('User u')
->orderby('u.id')
->execute();

Answer

Pascal MARTIN picture Pascal MARTIN · Dec 20, 2009

A solution might be to use the toArray() method on the $user object, to have a simple array containing only the data youre interested in, and, then, use json_encode to convert that PHP array to a JSON string.

Something like this, I suppose :

$user = Doctrine_Query::create()
->select('u.id, u.username, u.firstname, u.lastname')
->from('User u')
->orderby('u.id')
->execute();

$userArray = $user->toArray();
$json = json_encode($userArray);

(Not tested, but it should not be too far from working...)