【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!',
];

打賞做者

相關文章
相關標籤/搜索