【Yii2-CookBook】JSON 和 XML 輸出


Web 和移動應用程序現在不僅僅只是用來呈現 HTML。 現在開發一個移動客戶端,利用服務器 api 驅動前端,所有的用戶交互都在客戶端哪里。JSON 和 XML 格式通常用於序列化和傳輸結構化數據通過網絡,所以能夠創建這樣的響應是任何一個現代服務器框架的必備。

響應格式

正如你可能知道的,在 Yii2 中需要從你的 action return 結果,而不是直接回應:

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

好事是現在你可以從你的 action 直接返回不同類型的數據,即:

  • 數組
  • 一個實現 Arrayable 接口的對象
  • 一個字符串
  • 一個實現 __toString() 方法的對象。

只是別忘了告訴 Yii 做什么你想要的結果的格式,在 return 之前設置 \Yii::$app->response->format。例如:

\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 響應框:

結果

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

Note: 你會得到一個異常,如果沒有設置響應格式。

我們已經知道,我們也可以返回對象。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM