在php中合并XML文件 [英] Combining XML files in php
问题描述
我正在获取外部xml文件(通过文件交换),并且能够读取和存储在数据库中(php/mysql). xml文件使用不同的名称压缩,有时几个文件一起压缩在一个文件夹中
I am getting external xml files (through file exchange) and I am able to read and store in the database (php/mysql). The xml files come zipped under different names and sometimes several files come together zipped in a folder
当文件夹只有1个xml文件时,我能够使用
When the folder has only 1 xml file,I am able to successfully unzip and read the content using
$path = '/xmlFile';
//the xmlFile names are in this format : xmFile-00001235.xml,
//xmlFile-000012390.xml, etc. only first portions are consistent
foreach (glob($path.'/xmlFile-*.xml') as $filename)
{
$xml=file_get_contents($filename);
}
//store in database and unlink the xml file
这仅在文件夹具有一个xml文件的情况下有效,因为我在存储后取消链接该xml文件,它取消了所有文件的链接,但仅存储了一个文件.
This only works if the folder has one xml file, because I am un-linking the xml file after storage, it un-links all the files but only stores one
什么是最好的方法?我正在考虑检查文件夹中是否包含1个以上的xml并合并xml文件?也许一个示例解决方案确实会有所帮助,
What would be the best approach; I am thinking of checking if the folder has more than 1 xml and combine the xml files? maybe a sample solution will really help,
示例xml如下
xml1.xml
<sales>
<row id="000001" saleid="267158" amountSold="2000" />
<row id="000001" saleid="267159" amountSold="80.000" />
</sales>
xml2.xml
<sales>
<row id="000001" saleid="267160" amountSold="4000" />
<row id="000001" saleid="267161" amountSold="580" />
</sales>
推荐答案
可以合并多个文件,例如...
Merging several files can be done something like...
function mergeFile ( DOMDocument $target, $fileName ) {
$source = new DOMDocument();
$source->load($fileName);
foreach ( $source->getElementsByTagName("row") as $row ) {
$import = $target->importNode($row, true);
$target->documentElement->appendChild($import);
}
}
$target = new DOMDocument();
$target->loadXML('<?xml version="1.0" encoding="utf-8"?><sales></sales>');
mergeFile($target, "NewFile.xml");
mergeFile($target, "NewFile1.xml");
mergeFile($target, "NewFile2.xml");
$target->save("out2.xml");
这使您可以继续将所有文件添加在一起,然后最后保存它们.
This allows you to keep on adding all of the files together and then saving them at the end.
这篇关于在php中合并XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!