Php 修复用于转换为JSON的无效XML

Php 修复用于转换为JSON的无效XML,php,xml,regex,json,Php,Xml,Regex,Json,我试图将XML文档转换为JSON,但我遇到了一种情况,即有两种不同的数据类型,一种是删除另一种来解决这个问题。我尝试了一个正则表达式,在其中我得到了大部分的方法 我的问题是,有没有比使用正则表达式更好的方法来解决这个问题?我怎样才能解决这个问题 原始XML <StartMonthGroup> <StartMonth withdrawn="false"><MajorOfferRound>12 Dec 2013</MajorOfferRound>

我试图将XML文档转换为JSON,但我遇到了一种情况,即有两种不同的数据类型,一种是删除另一种来解决这个问题。我尝试了一个正则表达式,在其中我得到了大部分的方法

我的问题是,有没有比使用正则表达式更好的方法来解决这个问题?我怎样才能解决这个问题

原始XML

<StartMonthGroup>
   <StartMonth withdrawn="false"><MajorOfferRound>12 Dec 2013</MajorOfferRound>Sep 2013
   </StartMonth>
   <StartMonth withdrawn="false">Jan 2014</StartMonth>
   <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>
<StartMonthGroup>
  <MajorOfferRound>12 Dec 2013</MajorOfferRound>
  <StartMonth withdrawn="false">Sep 2013</StartMonth>
  <StartMonth withdrawn="false">Jan 2014</StartMonth>
  <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>

2013年12月12日第2013步
2014年1月
2014年5月
新XML

<StartMonthGroup>
   <StartMonth withdrawn="false"><MajorOfferRound>12 Dec 2013</MajorOfferRound>Sep 2013
   </StartMonth>
   <StartMonth withdrawn="false">Jan 2014</StartMonth>
   <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>
<StartMonthGroup>
  <MajorOfferRound>12 Dec 2013</MajorOfferRound>
  <StartMonth withdrawn="false">Sep 2013</StartMonth>
  <StartMonth withdrawn="false">Jan 2014</StartMonth>
  <StartMonth withdrawn="false">May 2014</StartMonth>
</StartMonthGroup>

2013年12月12日
2013年9月
2014年1月
2014年5月
PHP代码

public static function fixDates($data)
{
    if (preg_match("/<MajorOfferRound>/", $data)) {
        $data = preg_replace("/<StartMonth withdrawn=\"false\"><MajorOfferRound>/", "<MajorOfferRound>", $data);
        $data = preg_replace("/<\/MajorOfferRound>/", "</MajorOfferRound><StartMonth withdrawn=\"false\">", $data);

        $data = preg_replace("/<StartMonth withdrawn=\"true\"><MajorOfferRound>/", "<MajorOfferRound>", $data);
        $data = preg_replace("/<\/MajorOfferRound>/", "</MajorOfferRound><StartMonth withdrawn=\"true\">", $data);


        return $data;
    } else {
        return $data;
    }
}
公共静态函数fixDates($data)
{
if(预匹配(“/”,$data)){
$data=preg_replace(“//”、“”、$data);
$data=preg_replace(“//”、“”、$data);
$data=preg_replace(“//”、“”、$data);
$data=preg_replace(“//”、“”、$data);
返回$data;
}否则{
返回$data;
}
}

如果您认为正则表达式是一次完成所有替换的最佳方法

$regex = '/(<S\w{9}\sw\w{8}=\"\w{4,5}\">)(\W{1,2}M\w{14}>)(.*)(<\/M\w{14}>)(.*)\W+(<\/S\w{9}>)/im'; 

$result = preg_replace($regex, "$2$3$4\n   $1$5$6", $data);
$regex='/()(\W{1,2}M\W{14}>)(.*)(.*)(.*)(.*)W+()/im';
$result=preg_replace($regex,$2$3$4\n$1$5$6“,$data);

这就是它的作用:

你有没有尝试过这一点?基本上我已经有了它只是避免了两种数据类型