简体   繁体   中英

Using SimpleXmlElement and symfony2 to output xml file

$rootNode = new \SimpleXMLElement( "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><items></items>" );

$itemNode = $rootNode->addChild('item');
$itemNode->addChild( 'itemCode', 'mk' );
$itemNode->addChild( 'itemName', 'orange' );

$itemNode = $rootNode->addChild('item');
$itemNode->addChild( 'itemCode', 'ap' );
$itemNode->addChild( 'itemName', 'apple' );

$itemNode = $rootNode->addChild('item');
$itemNode->addChild( 'itemCode', 'tof' );
$itemNode->addChild( 'itemName', '豆腐' );


$itemNode->addAttribute('stock', 'none');

I made xml data with SimpleXMLElement.

then I want to output this on symfony2

return $rootNode->asXML();

return $this->render($rootNode->asXML());

Either doesnt work. How can I output xml file?

If you want to output data from controller you can do something like this:

<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class SomeController extends Controller
{
    public function someAction(Request $request)
    {
        $rootNode = new \SimpleXMLElement( "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><items></items>" );

        $itemNode = $rootNode->addChild('item');
        $itemNode->addChild( 'itemCode', 'mk' );
        // ...
        return new Response($rootNode->asXML());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM