Send JSON response with PHP

I am having a very hard time getting php to correctly echo JSON responses to be used in a javascript ajax call. The JSON responses are coming from the twitter-async library, which returns objects. I am trying to convert these objects to arrays then calling json_encode on them, but it is not working.


$home=$account->get_statusesHome_timeline(array('count' => 20, 'max_id' =>$id));
				
foreach($home as $tweet)
{
	echo json_encode(get_object_vars($tweet));
}

Here is the javascript code I am using to evaluate it:


function makeReadable(values)
{
	
	var json = eval('('+values+')');
	alert(json);
	
}


Currently the alert isn’t showing up no matter what I tried. I even tried getting the json call from twitter and putting it in the makeReadable function, but that didn’t work either. I don’t know which is wrong, the javascript or the php, or both, but I have been at this for way too long, without any results. Please help.

P.S. Also sorry for double-posting in the javascript forum, I will remove that shortly.

To find out which it is, debug them separately.

Run the PHP code directly, not through JavaScript, and look at its output.

If the PHP program produces the correct output, then start at the beginning of the JS. Verify you’re receiving that output by printing it (alert’s fine) before you do anything with it.

We can’t tell you what the proper json structure you need is.
We can tell you this is almost certainly wrong.


foreach($home as $tweet)
{
	echo json_encode(get_object_vars($tweet));
}

You generally only want to output a single return value of json_encode(), unless you feel like making things unnecessarily complex. So build up a php array that contains the data you need, in the structure you want, and call json_encode() a single time.

For example, maybe


$array = array();
foreach($home as $tweet)
{
	$array[] = get_object_vars($tweet);
}

echo json_encode(get_object_vars($tweet));

Why the foreach?? [fphp]json_encode[/fphp] can handle arrays and objects (subject to some limits) - so json_encode($home);

On the javascript side of things both jQuery and Prototype libraries have json handling features built in.

I actually was going about this the completely wrong way just doing this

echo ‘(’+$home->responseText.‘)’;

worked perfectly. Thanks for the input.

leosurf91, could you actually elaborate a little and show exactly what you’ve replaced your problematic code posted earlier with? I’m having a similar issue to what you had and was wondering what your full work around was. Thanks.