Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...