Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

php - Build and customize an XML file with Symfony serializer

I'm working on the Symfony serializer and I'm trying to generate an XML from the results of a query made on my Mongo database. But I want an XML with a very specific structure. I probably could do that by customizing XmlEncoder but it's probably more complicated than necessary.

I know I could change the default main tag <response> without editing the encoder class, just with a paramater but I haven't found how to customize the rest of the XML file, could I do it in this same way? I guess the answer is yes but I didn't find how to do.

This is the code of my controller:

public function servicesXml (ContentRepository $content): Response
  {
    $encoder = [new XmlEncoder ('result')];
    $normalizer = [new ObjectNormalizer ()];
    $serializer = new Serializer ($normalizer, $encoder);

    $response = $content-> getContents ();
$tag = [
      '@xmlns' => 'http://www.w3.org/2005/Atom',
      '#' => $response
    ];
    $response = $serializer-> serialize ($response, 'xml', [
  'xml_format_output' => true,
  'xml_encoding' => 'utf-8',
  'xml_root_node_name' => 'feed']);

    return new Response ($response);
  }

By default with XmlEncoder, I have something like :

<response>
    <item key="0">
        <id>1</id>
        <header>
            <title>Title</title>
            <subtitle>Subtitle</subtitle>
            <module>
                <date>
                    <time>-292277022657-01-27T08:29:52+0000</time>
                </date>
            </module>
            <author>
                <name>Name</name>
            </author>
        </header>
        <body>
                <html><![CDATA[<p>Text</p>]]></html>
            </body>
            <location>
                    <country_code>??</country_code>
                    <latitude>0</latitude>
                    <longitude>0</longitude>
                </location>
    </item>
</response>

and I hope to have :

<feed xlmns="http://www.w3.org/2005/Atom">
    <logo>URL</logo>
    <entry>
        <id>
        <title>Title</title>
        <notsubtitle>Subtitle</notsubtitle>
        <created>-292277022657-01-27T08:29:52+0000</created>
        <author>
            <name>Name</name>
        </author>
        <content type="xhtml">
            <div><p>Text</p></div>
        </content>
    </entry>
</feed>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...