添加 xml-样式表标签 simpleXML php



嘿伙计们,这是我的简单代码:

$xml = new SimpleXMLElement('<p:FatturazioneElettronica xmlns:p="http://microsoft.com/wsdl/types/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://dummy.com"/>');
$xml->addAttribute("versione","FPR12");
$FatturaElettronicaHeader = $xml->addChild('FatturaElettronicaHeader',null,'http://dummy.com');

XML 结果为:

<p:FatturazioneElettronica xmlns:p="http://microsoft.com/wsdl/types/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://dummy.com" versione="FPR12">
<FatturaElettronicaHeader>
<DatiTrasmissione>
....

如何在我的xml"xml样式表"的顶部添加?

<?xml-stylesheet type="text/xsl" href="fatturapa_v1.2.xsl" ?> 

SimpleXML除了简单的事情之外,并不擅长做任何事情(认为这个名字非常贴切(。 我能想到的唯一方法是使用 DOMDocument,它提供了一个更丰富的 API,你应该能够做到如下......

$xmlD = new DOMDocument( "1.0", "ISO-8859-15" );
$xmlD->appendChild($xmlD->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="fatturapa_v1.2.xsl"'));
$xmlD->appendChild($xmlD->importNode(dom_import_simplexml($xml)));
echo $xmlD->saveXML();

这将创建一个新的 DOMDocument 实例,然后添加一些内容。 首先,它使用createProcessingInstruction()为样式表添加处理指令。 然后,它会导入 SimpleXML 文档的现有内容(以$xml为单位(,并将其附加到末尾。echo应该给你一个类似这样的文件......

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="fatturapa_v1.2.xsl"?>
<p:FatturazioneElettronica xmlns:p="http://microsoft.com/wsdl/types/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://dummy.com" versione="FPR12"/>

最新更新