views:

151

answers:

3

With this code I am iterating through an object.

Works:

  • Windows with WAMP and PHP 5.2.9
  • Linux web server with PHP 5.2.10

It is not working on my desktop:

  • Ubuntu 9.10 with PHP 5.2.10-2 from the repo's
$incomingData = json_decode($_POST['data']);

foreach($incomingData as $key => $action)
{

}

Invalid argument supplied for foreach()

+2  A: 

Are you sure you've got your PHP versions right?

From the documentation for foreach:

As of PHP 5, it is possible to iterate objects too.

Try using json_decode with the second argument set to true, to make json_decode return associative arrays rather than objects.

$incomingData = json_decode($_POST['data'], true);

Where the second argument, $assoc (defaults to false) means:

When TRUE, returned objects will be converted into associative arrays.

My guess is that one box has less than PHP 5.

To confirm that's the issue, try changing $incomingData to some kind of innocuous associative array:

$incomingData = array("foo" => "bar", "baz" => "monkey");

and see if that makes the error go away.

Dominic Rodger
Thanks for your response. I'm sure I got the versions right. I added the argument to json_decode and edited my code but it produces the same error.
richard
+3  A: 

Maybe one of your servers has magic_quotes_gpc enabled, so you can try to use stripslashes on $_POST['data'] before you decode it. Both PHP versions should be able to iterate through objects.

Wessel Rossing
If this fixes it, you really ought to fix whichever server has magic_quotes_gpc enabled, and turn it off (see http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc)
Dominic Rodger
+1 for the good catch. =)
David Thomas
Thanks! Adding stripslashes did the trick! The data I was decoding had indeed backslashes in it.
richard
A: 

try doing:

$data_array = get_object_vars(json_decode($json_data));

print_r($data_array);

this is only if you obtain information from some web page such as

$data = file_get_contents('http://www.someurl.com/somerestful_url/');
$data_array = get_object_vars(json_decode($data));
print_r($data_array);

also, you were probably trying to do json_encode, but instead put json_decode($_POST['data']);

unless you have json string inside of $_POST['data']; it will not work.

krob