添加<!DOCTYPE to serialized xml from symfony serializer

问题描述 投票:0回答:1

symfony serializer中有xmlencoder,通过使用它我们可以实现这一点。

$data = ['foo' => 'Foo value'];
$encoder = new XmlEncoder();
$encoder->encode($data, 'xml');

// is encoded as follows:
// <?xml version="1.0"?>
// <response>
//     <foo>
//        Foo value
//     </foo>
// </response>

现在我们需要添加如下所示的内容

// is encoded as follows:
// <?xml version="1.0"?>
// <!DOCTYPE response SYSTEM "pathto.dtd">
// <response>
// .....

有没有办法用 symfony 序列化器来实现这一点?

php serialization xmlserializer symfony-serializer
1个回答
0
投票

不幸的是,Symfony Serializer 的

XmlEncoder
没有内置机制来将
<!DOCTYPE>
声明添加到生成的 XML 中。但是,您可以通过对序列化的 XML 输出进行后处理来实现此目的。本质上,您需要修改生成的 XML 字符串,以在 XML 声明 (
<!DOCTYPE>
) 之后包含
<?xml version="1.0"?>
声明。

以下是如何使用快速自定义函数执行此操作的示例:

public function addDoctypeToXml(string $xmlString, string $doctype): string
{
    // Append the provided DOCTYPE declaration after the XML declaration
    $updatedXml = preg_replace(
        '/(<\?xml[^>]+\?>)/', // Match the XML declaration (e.g., <?xml version="1.0"?>)
        '$1' . PHP_EOL . $doctype, // Append the DOCTYPE declaration right after the match
        $xmlString,
        1 // Only replace the first occurrence
    );
    return $updatedXml;
}

您现在可以在序列化数据后使用此功能添加自定义 DOCTYPE。例如:

public function generateXmlWithDoctype($data, $context = [])
{
    // Step 1: Serialize the data using Symfony Serializer's XmlEncoder
    $serializer = new Serializer([], [new XmlEncoder()]);
    $xmlString = $serializer->serialize($data, 'xml', $context);

    // Step 2: Define your DOCTYPE declaration
    $doctype = '<!DOCTYPE response SYSTEM "path-to-your.dtd">';

    // Step 3: Add the DOCTYPE to the serialized XML
    return $this->addDoctypeToXml($xmlString, $doctype);
}
© www.soinside.com 2019 - 2024. All rights reserved.