2

I would like to convert an object 'Resonse' that contains an array with objects to a JSON string.

Example of the data structure:

$response = new model_ObjectReponse();
$error1 = new model_Message('error', 'test error 1');
$error2 = new model_Message('error', 'test error 2');
$error3 = new model_Message('error', 'test error 3');
$response->add($error1);
$response->add($error2);
$response->add($error3);
$output = json_encode($response);
print $output;

The message objects have the private properties type and message with getters and setters.

So does anybody know how to convert this to a json string? Btw, I have the same question for converting it to XML.

Thanks for the help.

user5706
  • 103
  • 1
  • 6

3 Answers3

0

Check http://php.net/manual/en/function.serialize.php

This method will allow you to save object as string. You can also unserialize object, anyway storing objects as string is not a good practice.

Norbert Orzechowicz
  • 1,329
  • 9
  • 20
0

You can convert your Response object to an associative array and pass that array on to json_encode(). Something like this:

foreach ($response->getMessages() as $message)
  $responseArray['messages'][] = array(
    'type' => $message->getType(),
    'message' => $message->getMessage()
  );

json_encode($responseArray);

For the XML conversion, I wrote a simple class that can convert the $response array produced by the code above to a DOMDocument object or an XML string. You can find it here: code.google.com/p/array-to-domdocument/

Ohas
  • 1,887
  • 4
  • 21
  • 29
0

Your class definition could be the problem here. If you have private variables defined, a simple json_encode won't any usable output. You can created functions within your object to return a json-encoded string.

Web-Beest
  • 151
  • 6