Я хочу преобразовать SimpleXMLElement Object в XML в php - PullRequest
0 голосов
/ 25 апреля 2019

Я создал массив из 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 )
...