假设我有3个XML文件,如下所示:
dog.xml:
<animal>
<species>dog</species>
<weight>10</weight>
<length>2</length>
</animal>
cat.xml:
<animal>
<species>cat</species>
<weight>2.5</weight>
<length>1</length>
</animal>
rabbit.xml:
<animal>
<species>rabbit</species>
<weight>0.6</weight>
<length>0.3</length>
</animal>
我正在尝试将这3个组合成一个PHP文件,该文件可以作为.xml格式的网页提供,如下所示:
http://www.some.web.address.com/animals.php
<?xml version="1.0"?>
<animals>
<animal>
<species>dog</species>
<weight>10</weight>
<length>2</length>
</animal>
<animal>
<species>cat</species>
<weight>2.5</weight>
<length>1</length>
</animal>
<animal>
<species>rabbit</species>
<weight>0.6</weight>
<length>0.3</length>
</animal>
</animals>
以下规定适用:
- 顶部应该有一个xml版本标记,但是文件中其他地方不应该添加其他xml版本标记
- .xml标记格式必须显示
在整个
到目前为止,这是我能想到的最佳方式,这不是那么好:
<?php
$dogXml = simplexml_load_file("/some/file/location/dog.xml");
$catXml = simplexml_load_file("/some/file/location/cat.xml");
$rabbitXml = simplexml_load_file("/some/file/location/rabbit.xml");
echo "<pre>";
echo htmlspecialchars('<?xml version="1.0"?>');
echo "<br>";
echo htmlspecialchars("<animals>");
echo "<br>";
echo htmlspecialchars(explode("\n", $dogXml->asXML(), 2)[1]);
echo htmlspecialchars(explode("\n", $catXml->asXML(), 2)[1]);
echo htmlspecialchars(explode("\n", $rabbitXml->asXML(), 2)[1]);
echo htmlspecialchars("</animals>");
echo "</pre>";
?>
这会产生以下输出:
<?xml version="1.0"?>
<animals>
<animal>
<species>dog</species>
<weight>10</weight>
<length>2</length>
</animal>
<animal>
<species>cat</species>
<weight>2.5</weight>
<length>1</length>
</animal>
<animal>
<species>rabbit</species>
<weight>0.6</weight>
<length>0.3</length>
</animal>
</animals>
哪个是正确的,除了没有正确保留缩进(3个动物及其描述都应该缩进一个标签)。
此外,
explode("\n", $dogXml->asXML(), 2)[1]
抑制每个动物重新打印xml版本标签的技巧似乎在所有情况下都不起作用。
有没有更好的方法来实现这一目标?我能找到的关于这个主题的最好资料来自这些帖子:
remove xml version tag when a xml is created in php
但是这些帖子中的每个解决方案都会因错误而崩溃,没有保留xml标记,或者添加了其他内容(例如重复xml版本标记)。我可以从这些帖子中获得的唯一内容是上面的explode()调用。
建议?
答案 0 :(得分:1)
使用DOMDocument而不是SimpleXML可以让您轻松完成...
function mergeFile ( DOMDocument $target, $fileName ) {
$source = new DOMDocument();
$target->preserveWhiteSpace = false;
$source->load($fileName);
$import = $target->importNode($source->documentElement, true);
$target->documentElement->appendChild($import);
}
$target = new DOMDocument();
$target->formatOutput = true;
$target->preserveWhiteSpace = true;
$target->loadXML('<?xml version="1.0" encoding="utf-8"?><animals></animals>');
mergeFile($target, "dog.xml");
mergeFile($target, "cat.xml");
mergeFile($target, "rabbit.xml");
$target->loadXML($target->saveXML());
$target->save("animals.xml");
有一些小提琴可以确保格式正确,最后它会重新加载文档以创建正确的布局。此外,在加载子文档时,不会保留间距以允许主文档对其进行排序。
输出文件是......
<?xml version="1.0" encoding="utf-8"?>
<animals>
<animal>
<species>dog</species>
<weight>10</weight>
<length>2</length>
</animal>
<animal>
<species>rabbit</species>
<weight>0.6</weight>
<length>0.3</length>
</animal>
<animal>
<species>cat</species>
<weight>2.5</weight>
<length>1</length>
</animal>
</animals>