【问题标题】:how to convert a Array To Xml using php?如何使用 php 将数组转换为 Xml?
【发布时间】:2017-06-30 15:05:39
【问题描述】:

我需要使用 PHP 将数组转换为 XML。我尝试了以下方法,但无法使其正常工作。

Array
(
    [DateTimeStamp] => 06/30/2017 02:42:12
    [Sender] => Array
        (
            [SenderID] => TRN
            [SenderName] => compay
        )

    [Recipient] => Array
        (
            [RecipientID] => DATA1
            [RecipientName] => 
        )

    [TradingPartner] => Array
        (
            [TradingPartnerCode] => WEB01
            [TradingPartnerName] => 
        )

    [Customer] => Array
        (
            [CustomerNumber] => 42074
            [CustomerName] => 
        )

    [Message] => Array
        (
            [MessageID] => RSPRAT
            [MessageDescription] => Respond With Rates
        )

    [Payload] => Array
        (
            [RateProduct] => Array
                (
                    [0] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 13
                            [RentalLocationID] => 262
                            [RateCompanyID] => RCR
                            [RateCompanyName] => company
                            [BusinessHoursPickup] => 0730-2330,
                            [BusinessHoursReturn] => 0730-2330,
                            [SeasonalRate] => FCAR
                            [Government] => N
                            [ClassDesc] => Economy 2/4 Door Automatic With AC
                            [ModelDesc] => Sonata
                            [RateCode] => 1DAY
                            [CH] => H
                            [RateStartDate] => 06/30/2017
                            [RateEndDate] => 07/03/2017
                            [RateDescription] => 1DAY
                            [RatePlan] => DAILY
                            [MileageUnit] => KM
                            [CurrencyCode] => CAD
                            [RateAmount] => 127.50
                            [FreeMiles] => 0
                            [PerMileAmount] => 0.00

                            [ClassImageURL2] => 
                            [TotalPricing] => Array
                                (
                                    [RentalDays] => 1
                                    [RateCharge] => 127.50

                                    [Surcharge] => 0.0000
                                    [Taxes] => Array
                                        (
                                            [Tax2Amount] => 154.04
                                            [Tax2Rate] => 0.13
                                            [Tax2Desc] => H.S.T
                                            [Tax2Charge] => 20.03
                                            [Tax2Type] => PERCENT
                                        )

                                    [0] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [1] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [2] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [3] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )


                                    [RatePeriod] => Array
                                        (
                                            [Hours] => 0
                                            [AmtPerHour] => 0.00
                                            [Rate1Days] => 1
                                            [Rate1PerDay] => 127.50
                                            [Rate1Free] => 0
                                            [Rate2Days] => 0
                                            [Rate2PerDay] => 148.50
                                            [Rate2Free] => 0
                                            [Rate3Days] => 0
                                            [Rate3Per]=> 0.00
                                            [Months] => 0
                                            [AmtPerMonth] => 0.00
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 15
                            [RentalLocationID] => 266
                            [RateCompanyID] => RCR
                            [RateCompanyName] => Routes Car Renttals
                            [BusinessHoursPickup] => 0730-2330,
                            [BusinessHoursReturn] => 0730-2330,
                            [SeasonalRate] => ECAR
                            [Government] => N

                            [Passengers] => 5
                            [Luggage] => 3
                            [ClassImageURL] => upload/car_img/
                            [ClassImageURL2] => 
                            [TotalPricing] => Array
                                (
                                    [RentalDays] => 1
                                    [RateCharge] => 127.50
                                    [RatePlusLate] => 127.50
                                    [LateCharge] => 0.00
                                    [Surcharge] => 0.0000
                                    [Taxes] => Array
                                        (
                                            [Tax2Amount] => 154.04
                                            [Tax2Rate] => 0.13
                                            [Tax2Desc] => H.S.T
                                            [Tax2Charge] => 20.03
                                            [Tax2Type] => PERCENT
                                        )

                                    [0] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [1] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [2] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [3] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [4] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [5] => Array
                                        (
                                            [DailyExtra] => Array
                                                (
                                                    [ExtraCode] => ERF
                                                    [ExtraDesc] => ENERGY RECOVERY FEES
                                                    [ExtraAmount] => 1.00
                                                    [ExtraAutoApply] => TRUE
                                                )

                                        )

                                    [RatePeriod] => Array
                                        (
                                            [Hours] => 0
                                            [AmtPerHour] => 0.00
                                            [Rate1Days] => 1
                                            [Rate1PerDay] => 127.50
                                            [Rate1Free] => 0
                                            [AmtPerWeek] => 0.00
                                            [Months] => 0
                                            [AmtPerMonth] => 0.00
                                        )

                                )

                        ))))

我需要得到如下格式的 XML

<?xml version="1.0" encoding="UTF-8"?>
<PRE>
    <TRNXML Version="1.0.0">
        <DateTimeStamp TimeZone="ET">06/28/2017 03:36:56</DateTimeStamp>
        <Sender>
            <SenderID>TRN</SenderID>
            <SenderName>Transportation Reservation System,Inc.</SenderName>
        </Sender>
        <Recipient>
            <RecipientID>DATA1</RecipientID>
            <RecipientName />
        </Recipient>
        <TradingPartner>
            <TradingPartnerCode>WEB01</TradingPartnerCode>
            <TradingPartnerName />
        </TradingPartner>
        <Customer>
            <CustomerNumber>42074</CustomerNumber>
            <CustomerName />
        </Customer>
        <Message>
            <MessageID>RSPRAT</MessageID>
            <MessageDescription>Respond With Rates</MessageDescription>
        </Message>
        <Payload>
            <RateProduct>
                <RateVendor>42074</RateVendor>
                <RateID>29798021</RateID>
                <RentalLocationID>YYZ</RentalLocationID>
                <RateCompanyID>RCR</RateCompanyID>
                <RateCompanyName>Routes Car Renttals</RateCompanyName>
                <BusinessHoursPickup>0730-2330,</BusinessHoursPickup>
                <BusinessHoursReturn>0730-2330,</BusinessHoursReturn>
                <ClassCode>ECAR</ClassCode>
                <SeasonalRate>N</SeasonalRate>
                <Government>N</Government>
                <ClassDesc>Economy 2/4 Door Automatic With AC</ClassDesc>
                <ModelDesc>Kia Rio</ModelDesc>
                <RateCode>1DAY</RateCode>
                <CH>H</CH>
                <RateStartDate>06/28/2017</RateStartDate>
                <RateEndDate>07/03/2017</RateEndDate>
                <RateDescription>1DAY</RateDescription>
                <RatePlan>DAILY</RatePlan>
                <MileageUnit>KM</MileageUnit>
                <CurrencyCode>CAD</CurrencyCode>
                <RateAmount>127.50</RateAmount>
                <FreeMiles>0</FreeMiles>
                <PerMileAmount>0.00</PerMileAmount>
                <ExtraDayRate>148.50</ExtraDayRate>
                <ExtraDayFreeMiles>0</ExtraDayFreeMiles>
                <PerHourCharge>0.00</PerHourCharge>
                <RateAdjustment>0.50</RateAdjustment>
                <MaxTime>1</MaxTime>
                <MinTime>1</MinTime>
                <NextTierRate>0.00</NextTierRate>
                <NextTierFree>0</NextTierFree>
                <CardRequired>True</CardRequired>
                <MinimumAge>21</MinimumAge>
                <MaximumAge>74</MaximumAge>
                <Passengers>5</Passengers>
                <Luggage>3</Luggage>
                <ClassImageURL>carimages/ECAR.jpg</ClassImageURL>
                <ClassImageURL2>carimages/ECAR.jpg</ClassImageURL2>
                <TotalPricing>
                    <RentalDays>1</RentalDays>
                    <RateCharge>127.50</RateCharge>
                    <RatePlusLate>127.50</RatePlusLate>
                    <TotalCharges>174.07</TotalCharges>
                    <TotalTaxes>20.03</TotalTaxes>
                    <TotalExtras>26.54</TotalExtras>
                    <TotalFreeMiles>0</TotalFreeMiles>
                    <PerMileAmount>0.00</PerMileAmount>
                    <LateCharge>0.00</LateCharge>
                    <Surcharge>0.0000</Surcharge>
                    <Taxes>
                        <Tax2Amount>154.04</Tax2Amount>
                        <Tax2Rate>0.13</Tax2Rate>
                        <Tax2Desc>H.S.T</Tax2Desc>
                        <Tax2Charge>20.03</Tax2Charge>
                        <Tax2Type>PERCENT</Tax2Type>
                    </Taxes>
                    <DailyExtra>
                        <ExtraCode>ERF</ExtraCode>
                        <ExtraDesc>ENERGY RECOVERY FEES</ExtraDesc>
                        <ExtraAmount>1.00</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>FC</ExtraCode>
                        <ExtraDesc>FUEL CONSERVATION</ExtraDesc>
                        <ExtraAmount>0.80</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>OEF</ExtraCode>
                        <ExtraDesc>ONTARIO ENVIRONMENT FEE</ExtraDesc>
                        <ExtraAmount>1.00</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>PLS</ExtraCode>
                        <ExtraDesc>PREFERED LOCATION SURCHARGE</ExtraDesc>
                        <ExtraAmount>17.79</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>VLF</ExtraCode>
                        <ExtraDesc>VEHICLE LICENSING FEE</ExtraDesc>
                        <ExtraAmount>5.95</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <RatePeriod>
                        <Hours>0</Hours>
                        <AmtPerHour>0.00</AmtPerHour>
                        <Rate1Days>1</Rate1Days>
                        <Rate1PerDay>127.50</Rate1PerDay>
                        <Rate1Free>0</Rate1Free>
                        <Rate2Days>0</Rate2Days>
                        <Rate2PerDay>148.50</Rate2PerDay>
                        <Rate2Free>0</Rate2Free>
                        <Rate3Days>0</Rate3Days>
                        <Rate3PerDay>148.50</Rate3PerDay>
                        <Rate3Free>0</Rate3Free>
                        <Weekends>0</Weekends>
                        <AmtPerWeekend>0.00</AmtPerWeekend>
                        <Weeks>0</Weeks>
                        <AmtPerWeek>0.00</AmtPerWeek>
                        <Months>0</Months>
                        <AmtPerMonth>0.00</AmtPerMonth>
                    </RatePeriod>
                </TotalPricing>
            </RateProduct>
            <RateProduct>
                <RateVendor>42074</RateVendor>
                <RateID>29798020</RateID>
                <RentalLocationID>YYZ</RentalLocationID>
                <RateCompanyID>RCR</RateCompanyID>
                <RateCompanyName>Routes Car Renttals</RateCompanyName>
                <BusinessHoursPickup>0730-2330,</BusinessHoursPickup>
                <BusinessHoursReturn>0730-2330,</BusinessHoursReturn>
                <ClassCode>CCAR</ClassCode>
                <SeasonalRate>N</SeasonalRate>
                <Government>N</Government>
                <ClassDesc>Compact 2/4 Door Automatic With AC</ClassDesc>
                <ModelDesc>Toyota Yaris</ModelDesc>
                <RateCode>1DAY</RateCode>
                <CH>H</CH>
                <RatePlan>DAILY</RatePlan>
                <MileageUnit>KM</MileageUnit>
                <CurrencyCode>CAD</CurrencyCode>
                <RateAmount>135.00</RateAmount>
                <FreeMiles>0</FreeMiles>
                <PerMileAmount>0.00</PerMileAmount>
                <ExtraDayRate>148.50</ExtraDayRate>
                <ExtraDayFreeMiles>0</ExtraDayFreeMiles>
                <PerHourCharge>0.00</PerHourCharge>
                <RateAdjustment>0.50</RateAdjustment>
                <MaxTime>1</MaxTime>
                <MinTime>1</MinTime>
                <NextTierRate>0.00</NextTierRate>
                <NextTierFree>0</NextTierFree>
                <CardRequired>True</CardRequired>
                <MinimumAge>21</MinimumAge>
                <MaximumAge>74</MaximumAge>
                <Passengers>5</Passengers>
                <Luggage>3</Luggage>
                <ClassImageURL2>carimages/CCAR.jpg</ClassImageURL2>
                <TotalPricing>
                    <RentalDays>1</RentalDays>
                    <RateCharge>135.00</RateCharge>
                    <RatePlusLate>135.00</RatePlusLate>
                    <TotalCharges>183.72</TotalCharges>
                    <TotalTaxes>21.14</TotalTaxes>
                    <TotalExtras>27.58</TotalExtras>
                    <TotalFreeMiles>0</TotalFreeMiles>
                    <PerMileAmount>0.00</PerMileAmount>
                    <LateCharge>0.00</LateCharge>
                    <Surcharge>0.0000</Surcharge>
                    <Taxes>
                        <Tax2Amount>162.58</Tax2Amount>

                        <Tax2Charge>21.14</Tax2Charge>
                        <Tax2Type>PERCENT</Tax2Type>
                    </Taxes>
                    <DailyExtra>
                        <ExtraCode>ERF</ExtraCode>
                        <ExtraDesc>ENERGY RECOVERY FEES</ExtraDesc>
                        <ExtraAmount>1.00</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>FC</ExtraCode>
                        <ExtraDesc>FUEL CONSERVATION</ExtraDesc>
                        <ExtraAmount>0.80</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>OEF</ExtraCode>
                        <ExtraDesc>ONTARIO ENVIRONMENT FEE</ExtraDesc>
                        <ExtraAmount>1.00</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>PLS</ExtraCode>
                        <ExtraDesc>PREFERED LOCATION SURCHARGE</ExtraDesc>
                        <ExtraAmount>18.83</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <DailyExtra>
                        <ExtraCode>VLF</ExtraCode>
                        <ExtraDesc>VEHICLE LICENSING FEE</ExtraDesc>
                        <ExtraAmount>5.95</ExtraAmount>
                        <ExtraAutoApply>TRUE</ExtraAutoApply>
                    </DailyExtra>
                    <RatePeriod>
                        <Hours>0</Hours>

                        <Rate2PerDay>148.50</Rate2PerDay>
                        <Rate2Free>0</Rate2Free>
                        <Rate3Days>0</Rate3Days>
                        <Rate3PerDay>148.50</Rate3PerDay>
                        <Rate3Free>0</Rate3Free>
                        <Weekends>0</Weekends>
                        <AmtPerWeekend>0.00</AmtPerWeekend>
                        <Weeks>0</Weeks>
                        <AmtPerWeek>0.00</AmtPerWeek>
                        <Months>0</Months>
                        <AmtPerMonth>0.00</AmtPerMonth>
                    </RatePeriod>
                </TotalPricing>
            </RateProduct>
        </Payload>
    </TRNXML>
</PRE>

目前我写的代码如下所示

// function defination to convert array to xml
        function array_to_xml($template_info, &$xml_template_info) {
            foreach($template_info as $key => $value) {
                if(is_array($value)) {
                    if(!is_numeric($key)){

                        $subnode = $xml_template_info->addChild("$key");

                        if(count($value) >1 && is_array($value)){
                            $jump = false;
                            $count = 1;
                            foreach($value as $k => $v) {
                                if(is_array($v)){
                                    if($count++ > 1)
                                        $subnode = $xml_template_info->addChild("$key");

                                    array_to_xml($v, $subnode);
                                    $jump = true;
                                }
                            }
                            if($jump) {
                                goto LE;
                            }
                            array_to_xml($value, $subnode);
                        }
                        else
                            array_to_xml($value, $subnode);
                    }
                    else{
                        array_to_xml($value, $xml_template_info);
                    }
                }
                else {
                    $xml_template_info->addChild("$key","$value");
                }

                LE: ;
            }
        }

        // creating object of SimpleXMLElement
        $xml_template_info = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><PRE><TRNXML Version=\"1.0.0\"></TRNXML></PRE>");

        // function call to convert array to xml

        // here i am calling the array values to convert xml
        array_to_xml($result_arr,$xml_template_info);

        //saving generated xml file
        $xml_file = $xml_template_info->asXML($_SERVER['DOCUMENT_ROOT']."/requests_ci_api/upload/manifest1.xml") ;

        /*if($xml_file){
                echo 'XML file have been generated successfully.';
            }else{
                echo 'XML file generation error.';
            }*/

        }

【问题讨论】:

    标签: php arrays xml codeigniter


    【解决方案1】:

    递归是你的朋友:

    function arrayToXml(array $a)
    {
        $xml = '';
        foreach ($a as $k => $v) {
            $xml .= '<' . $k . '>';
            if (gettype($v) === 'array') {
                $xml .= arrayToXml($v);
            } else {
                $xml .= $v;
            }
            $xml .= '<' . $k . '/>';
        }
        return $xml;
    }
    

    这只会给你一个带有 xml 的字符串。

    【讨论】:

      【解决方案2】:

      请注意,如果您的数组是数字索引的,则以下内容将不起作用。

      /**
       * @param $data
       * @param boolean $includeHeaderFooter
       * @return string
       */
      public function arrayToXmlConversion($data, $includeHeaderFooter = true)
      {
          $xml = '';
          if ($includeHeaderFooter === true) {
              $xml .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
              $xml .= "<result>";
          }
          foreach ($data as $key => $value) {
              $xml .= "<{$key}>";
              if ($this->isIterable($value)) {
                  $xml .= $this->arrayToXmlConversion($value, false);
              } else {
                  $xml .= $value;
              }
              $xml .= "</{$key}>";
          }
          if ($includeHeaderFooter === true) {
              $xml .= "</result>";
          }
          return $xml;
      }
      
      
      /**
       * Determine if a given data is iterable.
       * @param $data
       * @return bool
       */
      public function isIterable($data)
      {
          if ($this->isJson($data)) {
              $data = json_decode($data, 1);
          }
          if (is_array($data) || is_object($data)) {
              return true;
          }
          return false;
      }
      
      /**
       * Try to json_decode a string, if there is no error
       * the string must be JSON.
       *
       * @param $data
       * @return bool
       */
      public function isJson($data)
      {
          if (is_string($data)) {
              json_decode($data);
              return (json_last_error() == JSON_ERROR_NONE);
          }
          return false;
      }
      

      【讨论】:

      • 我确实有这个 Gist 可以做更多的事情,你可以使用链接的 Gist 以便数字索引数组也可以工作。 gist.github.com/ajaypayne/e190b11204ee4764926cdde429cecd0b
      • 谢谢兄弟的回复。但我同时使用数字和非数字如何完成请帮助我。我在这里卡了这么久..
      • 见我之前的评论,使用这个要点和链接的要点数字索引数组也可以工作。 gist.github.com/ajaypayne/e190b11204ee4764926cdde429cecd0b 加上你会得到一些其他很酷的东西,你可以在不同数据类型之间进行转换
      猜你喜欢
      • 2019-09-07
      • 2018-07-30
      • 2011-12-25
      • 2015-09-03
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多