有一个插件可以形成用于导出商品的XML文件。但无论我怎么努力,我都无法在行的开头插入代码<?xml version = "1.0" encoding = "utf-8"?>
。不幸的是,有必要对文件进行验证。现在以这种方式产生:
<root>
<object>
<objectid></objectid>
<title></title>
<type></type>
...
</object>
<object>...</object>
...
</root>
我不是这个问题的专业人士,但我只会给出一段可能出现问题的代码:
public function onAjaxBTExport()
{
$xml = new SimpleXMLElementExtended('<root/>');
....
$data = $xml->asXML();
file_put_contents(JPATH_SITE.'/data.xml', $data);
header('Content-type: text/xml');
echo $data;
die;
}
class SimpleXMLElementExtended extends SimpleXMLElement
{
private function addCDataToNode(SimpleXMLElement $node, $value = '')
{
if ($domElement = dom_import_simplexml($node))
{
$domOwner = $domElement->ownerDocument;
$domElement->appendChild($domOwner->createCDATASection("{$value}"));
}
}
public function addChildWithCData($name = '', $value = '')
{
$newChild = parent::addChild($name);
if ($value) $this->addCDataToNode($newChild, "{$value}");
return $newChild;
}
public function addCData($value = '')
{
$this->addCDataToNode($this, "{$value}");
}
}
答案 0 :(得分:0)
考虑使用XSLT模板运行identity tranform(XML转换语言),该模板按原样复制整个文档,然后将 omit-xml-declaration 显式设置为&# 34;无&#34 ;.这样做的另一个好处就是打印输出。
要在PHP中运行XSLT 1.0,请确保在.ini文件中启用php-xsl扩展名。 XSLT下面嵌入了字符串,但可以从文件中解析。
$xml = new SimpleXMLElementExtended('<root/>');
...
$data = $xml->asXML();
// LOAD XML SOURCE
$doc = new DOMDocument;
$doc->loadXML($data);
// LOAD XSLT SOURCE
$xsl = new DOMDocument;
$xsl->loadXML('<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" omit-xml-declaration="no" indent="yes" />
<xsl:strip-space elements="*"/>
<!-- Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:transform>');
// CONFIGURE TRANSFORMER
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
// RUN TRANSFORMATION
$newXML = $proc->transformToXML($doc);
// ECHO TO CONSOLE
header('Content-type: text/xml');
echo $newXML;
// SAVE TO FILE
file_put_contents(JPATH_SITE.'/data.xml', $newXML);