【Yii2-CookBook】JSON 和 XML 输出

使用不一样的响应类型

Web 和移动应用程序如今不单单只是用来呈现 HTML。 如今开发一个移动客户端,利用服务器 api 驱动前端,全部的用户交互都在客户端哪里。JSON 和 XML 格式一般用于序列化和传输结构化数据经过网络,因此可以建立这样的响应是任何一个现代服务器框架的必备。php

响应格式

正如你可能知道的,在 Yii2 中须要从你的 action return 结果,而不是直接回应:前端

// returning HTML result
return $this->render('index', [
    'items' => $items,
]);

好事是如今你能够从你的 action 直接返回不一样类型的数据,即:web

  • 数组
  • 一个实现 Arrayable 接口的对象
  • 一个字符串
  • 一个实现 __toString() 方法的对象。

只是别忘了告诉 Yii 作什么你想要的结果的格式,在 return 以前设置 \Yii::$app->response->format。例如:api

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

有效的格式:数组

  • FORMAT_RAW
  • FORMAT_HTML
  • FORMAT_JSON
  • FORMAT_JSONP
  • FORMAT_XML

默认是 FORMAT_HTML.服务器

JSON 响应

让咱们返回一个数组:网络

public function actionIndex()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $items = ['some', 'array', 'of', 'data' => ['associative', 'array']];
    return $items;
}

瞧!——咱们的 JSON 响应框:app

结果框架

{
    "0": "some",
    "1": "array",
    "2": "of",
    "data": ["associative", "array"]
}

Note: 你会获得一个异常,若是没有设置响应格式。yii

咱们已经知道,咱们也能够返回对象。

public function actionView($id)
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $user = \app\models\User::find($id);
    return $user;
}

如今 $user 是 实现 Arrayable 接口的类 ActiveRecord 的实例,因此它能够很容易地转换为 JSON:

结果

{
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com"
}

咱们甚至能够返回一个对象数组:

public function actionIndex()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $users = \app\models\User::find()->all();
    return $users;
}

如今 $users 是 ActiveRecord 对象数组,可是在下面 Yii 使用 \yii\helpers\Json::encode() 遍历数据传递和转换,照顾类型自己:

结果

[
    {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    },
    {
        "id": 2,
        "name": "Jane Foo",
        "email": "jane@example.com"
    },
    ...
]

XML 响应

响应格式改成 FORMAT_XML 这样。如今你有了 XML:

public function actionIndex()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    $items = ['some', 'array', 'of', 'data' => ['associative', 'array']];
    return $items;
}

结果

<response>
    <item>some</item>
    <item>array</item>
    <item>of</item>
    <data>
        <item>associative</item>
        <item>array</item>
    </data>
</response>

是的,咱们能够跟咱们以前作的同样转换对象和数组的对象。

public function actionIndex()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    $users = \app\models\User::find()->all();
    return $users;
}

结果

<response>
    <User>
        <id>1</id>
        <name>John Doe</name>
        <email>john@example.com</email>
    </User>
    <User>
        <id>2</id>
        <name>Jane Foo</name>
        <email>jane@example.com</email>
    </User>
</response>

自定义响应格式

让咱们建立一个定制的响应格式。例子作点有趣和疯狂的事我回应 PHP 数组。 首先,咱们须要格式化程序自己。建立components/PhpArrayFormatter.php

<?php
namespace app\components;

use yii\helpers\VarDumper;
use yii\web\ResponseFormatterInterface;

class PhpArrayFormatter implements ResponseFormatterInterface
{
    public function format($response)
    {
        $response->getHeaders()->set('Content-Type', 'text/php; charset=UTF-8');
        if ($response->data !== null) {
            $response->content = "<?php\nreturn " . VarDumper::export($response->data) . ";\n";
        }
    }
}

如今咱们须要在注册应用程序配置 (一般是 config/web.php):

return [
    // ...
    'components' => [
        // ...
        'response' => [
            'formatters' => [
                'php' => 'app\components\PhpArrayFormatter',
            ],
        ],
    ],
];

如今是准备使用。在 controllers/SiteController 建立一个新的方法 actionTest:

public function actionTest()
{
    Yii::$app->response->format = 'php';
    return [
        'hello' => 'world!',
    ];
}

就是这样。执行后,Yii 将回应如下:

<?php
return [
    'hello' => 'world!',
];

打赏做者

相关文章
相关标签/搜索