【问题标题】:PHP array with objects to json string带有对象到 json 字符串的 PHP 数组
【发布时间】:2012-03-25 18:52:20
【问题描述】:

我想将包含对象数组的对象“Resonse”转换为 JSON 字符串。

数据结构示例:

$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;

消息对象具有私有属性 type 和带有 getter 和 setter 的消息。

那么有人知道如何将其转换为 json 字符串吗?顺便说一句,我有同样的问题要将其转换为 XML。

感谢您的帮助。

【问题讨论】:

标签: php xml arrays json object


【解决方案1】:

查看http://php.net/manual/en/function.serialize.php

此方法将允许您将对象保存为字符串。您也可以反序列化对象,无论如何将对象存储为字符串不是一个好习惯。

【讨论】:

    【解决方案2】:

    您可以将 Response 对象转换为关联数组并将该数组传递给 json_encode()。像这样的:

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

    对于 XML 转换,我写了一个简单的类,可以将上面代码生成的$response 数组转换为 DOMDocument 对象或 XML 字符串。你可以在这里找到它:code.google.com/p/array-to-domdocument/

    【讨论】:

      【解决方案3】:

      您的类定义可能是这里的问题。如果您定义了私有变量,则简单的 json_encode 不会有任何可用的输出。您可以在对象中创建函数以返回 json 编码的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 2019-10-03
        相关资源
        最近更新 更多