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()
-
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 totrue
, to makejson_decode
return associative arrays rather than objects.$incomingData = json_decode($_POST['data'], true);
Where the second argument,
$assoc
(defaults tofalse
) 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.
richard : 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. -
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.
Dominic Rodger : 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)David Thomas : +1 for the good catch. =)richard : Thanks! Adding stripslashes did the trick! The data I was decoding had indeed backslashes in it. -
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.
0 comments:
Post a Comment