我想将SimpleXMLElement对象转换为php中的XML

时间:2019-04-25 08:34:00

标签: php xml simplexml

我已经从simplexml_load_string创建了一个数组,现在我想将其转换回XML

我尝试过

function convertSimpleXMLToArray($xml)
{
    if(class_basename($xml) == 'SimpleXMLElement')
    {
        $xml = get_object_vars($xml);
        foreach($xml as $key => $value)
        {
            if(class_basename($value) == 'SimpleXMLElement') $xml[$key] = convertSimpleXMLToArray($value);
        }
    }

    return $xml;
}

$result = convertSimpleXMLToArray($xml);

还有这个

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLElement('<root/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}


header('Content-type: text/xml');
print array2xml($test_array);

这是数组的一部分,我想将其转换为XML

Array ( [0] => SimpleXMLElement Object ( [uid] => S55 [type] => PACKAGE [serviceCode] => SLVKNKPRE [serviceCodeCMS] => SLVKNKBAI [name] => PREMIUM Experience the Northern Rhine - intern. ship [fromDate] => 2019-09-07T00:00:00.000+02:00 [endDate] => 2019-09-14T00:00:00.000+02:00 [dayService] => false [price] => SimpleXMLElement Object ( [totalPrice] => 1699.00 [totalPriceCurrency] => EUR [basePrice] => 1699.00 [basePriceCurrency] => EUR ) [isAlternativeSearch] => false [externalData] => SimpleXMLElement Object ( [extType] => P [extCategory] => 19941 [externalID] => SimpleXMLElement Object ( ) [touroperatorServiceId] => 19941 ) [destination] => SimpleXMLElement Object ( [destinationCode] => Rhine [destinationTypecode] => RIVER [destinationComposedDesc] => Rhine ) [serviceDescription] => SimpleXMLElement Object ( [description] => PREMIUM Experience the Northern Rhine - intern. ship ) [isDetailsIncluded] => false [duration] => 7 [hasRelatedServices] => false [services] => SimpleXMLElement Object ( [cruiseService] => SimpleXMLElement Object ( [uid] => S56 [type] => CRUISE [serviceCode] => SLVKNKPRE [serviceCodeCMS] => SLVKNKBAI [name] => A-ROSA SILVA PREMIUM Experience the Northern Rhine-int. ship [fromDate] => 2019-09-07T00:00:00.000+02:00 [endDate] => 2019-09-14T00:00:00.000+02:00 [dayService] => false [units] => SimpleXMLElement Object ( [uid] => U28 [category] => A [fromDate] => 2019-09-07T00:00:00.000+02:00 [endDate] => 2019-09-14T00:00:00.000+02:00 [freeUnits] => 4 [numberOfUnits] => 0 [occupancy] => SimpleXMLElement Object ( [occupancy] => 2 [occupancyMin] => 1 [occupancyMax] => 2 [occupancyDef] => 2 ) [totalPrice] => SimpleXMLElement Object ( [totalPrice] => 1699.00 [totalPriceCurrency] => EUR [basePrice] => 1699.00 [basePriceCurrency] => EUR [priceMode] => PERSON )

0 个答案:

没有答案