简体   繁体   English

如何使用php将数组转换为Xml?

[英]how to convert a Array To Xml using php?

I need to convert an array to XML using PHP. 我需要使用PHP将数组转换为XML。 I have tried the following method but I could not make it working properly. 我尝试了以下方法,但无法使其正常工作。

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
                                        )

                                )

                        ))))

And I need to get the XML like following format 我需要获取如下格式的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>

the code which i have written in so far is shown below 我到目前为止所写的代码如下所示

// 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.';
            }*/

        }

Recursion is your friend: 递归是您的朋友:

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;
}

That will just give you a string with the xml. 那只会给你一个带有xml的字符串。

Please note that the below will not work if your array is numerically indexed. 请注意,如果对数组进行数字索引,则以下内容将不起作用。

/**
 * @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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM