我正在尝试创建一个简单的 XML 到 JSON 转换器,从一个文件夹读取并输出到另一个。这个过程似乎工作正常,但我似乎无法让这个东西包含 XML 的根标记。请在下面找到示例:
<?php
$inputFolder = new FilesystemIterator("C:/folder/XML to JSON/Input");
$outputFolder = ("C:/XML to JSON/Output/");
//for new filename
$extensionToRemove = array(".xml");
foreach ($inputFolder as $xmlFile) {
//purely file name related
$theFileNameAndExtension = $xmlFile->getFilename();
$theFileName = str_replace($extensionToRemove, "", $theFileNameAndExtension);
//load xml file from disk
$xmlFileLoaded = simplexml_load_file($xmlFile);
//json encode the xml
$jsonResult = json_encode($xmlFileLoaded, JSON_FORCE_OBJECT | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_PRETTY_PRINT);
//save new json file to disk
file_put_contents($outputFolder.$theFileName.".json", $jsonResult);
//print out each file name as they are completed
echo $theFileName."<br>";
}
echo 'Done with all files.';
从磁盘读取的示例 XML 输入:
<?xml version= "1.0" encoding="UTF-8"?>
<RootArea>
<TransactionNum>
<TranNum>20180501_11355088774_001</TranNum>
<TranDate>20180501</TranDate>
</TransactionNum>
<SectionA>
<Type>Type A</Type>
<Name>Example Name</Name>
<Num>04419883333</Num>
<Code>MP0614343</Code>
<AnotherCode>0140000422053</AnotherCode>
</SectionA>
<SectionB>
<TotTarItems>3333</TotTarItems>
<TotModItems>3333</TotModItems>
<TotTarAmount>55555</TotTarAmount>
<TotModAmount>222</TotModAmount>
</SectionB>
</RootArea>
示例 JSON 输出成功保存到磁盘:
{
"TransactionNum": {
"TranNum": "20180501_11355088774_001",
"TranDate": "20180501"
},
"SectionA": {
"Type": "Type A",
"Name": "Example Name",
"Num": "04419883333",
"Code": "MP0614343",
"AnotherCode": "0140000422053"
},
"SectionB": {
"TotTarItems": "3333",
"TotModItems": "3333",
"TotTarAmount": "55555",
"TotModAmount": "222"
}
}
我非常希望这个过程能简单地将我的示例<RootArea></RootArea>
标签包含在输出中,但我尝试过的任何尝试都没有奏效。