Question

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()

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top