我正在尝试创建一个简单的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>
标签,但是我没有尝试过。
答案 0 :(得分:1)
您可以通过在当前根节点顶部添加另一个虚拟根xml节点来解决此问题,如下所示:
$xmlstr = str_replace('<?xml version= "1.0" encoding="UTF-8"?>','<?xml version= "1.0" encoding="UTF-8"?><newroot>',file_get_contents($xmlFile))."</newroot>";
$xmlFileLoaded = simplexml_load_string($xmlstr);
答案 1 :(得分:1)
simple_load_xml()
方法采用隐式根级别,因此除非您自己明确添加它,否则不会将其添加到您的json中。有几种方法可以解决此问题,但这是一种丑陋的方法,不会与您的xml混淆,并保持原始的json_encode方法不变:
//load xml file from disk
$xmlFileLoaded = simplexml_load_file($xmlFile);
$root = $xmlFileLoaded->getName(); // this grabs the root of your xml
//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);
// wrap your json with the root element. Ugly, yes, but it gets the job done
$finaloutput = json_encode( array($root => json_decode($jsonResult) ) )
//save new json file to disk
file_put_contents( $outputFolder.$theFileName.".json", $finaloutput );