Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 render response a xml file in the view

Tags:

xml

yii2

Does anyone know how can I show a .xml response file in the view? Render that xml as a html?

A have found something like this:

http://code.google.com/p/yii/source/browse/trunk/framework/web/widgets/CTextHighlighter.php

I am not sure if it can help me, because it is for an old version of the Yii...

like image 797
Lackeeee Avatar asked Nov 19 '15 10:11

Lackeeee


Video Answer


2 Answers

With reference to Fabrizio's solution, this will allow you to edit styling via .css:

Load and output the xml in the view:

/views/site/xml.php

<?php echo file_get_contents(Yii::getAlias('@app/web/').'doc.xml');

As you can see, I put my XML document into the web folder, you can adjust this to your requirements.

In controller, create the action to display the view:

public function actionXml() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
    Yii::$app->response->headers->add('Content-Type', 'text/xml');
    return $this->renderPartial('xml');
}

Notice that FORMAT_XML method of the \yii\web\Response class, mentioned in Fabrizio's solution will wrap your XML in <response>...</response> tags, and including your actual data as text in a <span>...</span>.

Instead, make sure that you have reference to a stylesheet in your XML markup:

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="/css/doc.css"?>

Once again, feel free to adjust the location of the .css as per your needs.

In your .css file, simply refer to your XML entities as you would with HTML tags:

RootEntity {
    display: block;
}

Hope this helps!

like image 91
bds Avatar answered Sep 21 '22 03:09

bds


In the controller action put

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

Remember to render the view using renderPartial() instead render(), so the layout will not be applied.

Finally in the view put the xml code.

For example:

Controller:

public function actionTest()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;

    return $this->renderPartial('test');
}

View:

<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
</Tests>

That's all!

like image 24
Fabrizio Caldarelli Avatar answered Sep 25 '22 03:09

Fabrizio Caldarelli