Jump to content

Convert array into xml


robandrox

Recommended Posts

sure, just loop through your array.

it would help to know what the array looks like though.

 

Here the just of what you need to do...

 

<?php
$myArray['dimension1']['part1'][key1] = "some Value";
$myArray['dimension1']['part1'][key2] = "some Value";
$myArray['dimension1']['part2'][key1] = "some Value";


foreach($myArray as $dimension => $part){ ?>

< <?php echo $dimension ?> >
< <?php echo part ?>

<?php  foreach($part as $key => $value){ ?>
   < <?php echo key ?> > <?php echo value ?></ <?php echo key ?> >
  }
</ <?php echo dimension ?> >
</ <?php echo part ?> >

<?php } ?>

I can´t attach any file so I write here the xml file and the code that converts it into a multidemensional array.The goal is convert the array into an xml file again.

The xml file:

<config>
       <objects>
           <object id="absence" gad="1/1/60" init="request">Absence</object>
           <object id="alarm_active" init="on">Alarme activée</object>
           <object id="ecl_escalier" gad="1/1/6">Eclairage Escalier
               <listener gad="1/1/206"/>
           </object>
           <object id="status_ecl_escalier" gad="1/1/206">Eclairage Escalier (status feedback)</object>
        </objects>
     <rules>
         <rule id="cur_time_date">
             <condition type="timer" trigger="true">
                 <every>3600</every>
             </condition>
             <actionlist>
                 <action type="set-value" id="cur_time" value="now" />
                 <action type="set-value" id="cur_date" value="now" />
             </actionlist>
         </rule>
       </rules>
</config>

And this the code that converts it into an array:

function xmlToarray($contents,$get_attributes=1) {


    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }
    //Obtiene el parser XML de PHP
    $parser = xml_parser_create();
    xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
    xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
    xml_parse_into_struct( $parser, $contents, $xml_values );
    xml_parser_free( $parser );

    if(!$xml_values) return;


    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array;

    //Recorre los tags
    foreach($xml_values as $data) {
        unset($attributes,$value);//Borra los valores existentes

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = '';
        if($get_attributes) {//El segundo argumento de la función decide ésto.
            $result = array();
            if(isset($value)) $result['value'] = $value;

            //Establece los atributos
            if(isset($attributes)) {
                foreach($attributes as $attr => $val) {
                    if($get_attributes == 1) $result[$attr] = $val; //Set all the attributes in a array called 'attr'
                    /**  :TODO: should we change the key name to '_attr'? Someone may use the tagname 'attr'. Same goes for 'value' too */
                }
            }
        } elseif(isset($value)) {
            $result = $value;
        }

        //Ve el estado del tag y hace lo necesario
        if($type == "open") {//Comienzo del tag '<tag>'
            $parent[$level-1] = &$current;

            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Introducimos nuevo tag
                $current[$tag] = $result;
                $current = &$current[$tag];

            } else { //Había otro elemento con el mismo nombre del tag
                if(isset($current[$tag][0])) {
                    array_push($current[$tag], $result);
                } else {
                    $current[$tag] = array($current[$tag],$result);
                }
                $last = count($current[$tag]) - 1;
                $current = &$current[$tag][$last];
            }

        } elseif($type == "complete") { //Tags que acaban en una línea '<tag />'
            //Comprueba si la clave se ha cogido ya
            if(!isset($current[$tag])) { //Nueva clave
                $current[$tag] = $result;

            } else { //If taken, put all things inside a list(array)
                if((is_array($current[$tag]) and $get_attributes == 0)//Si es ya un array...
                        or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
                    array_push($current[$tag],$result); // ...mete el nuevo elemento en el array.
                } else { //Si no es un array...
                    $current[$tag] = array($current[$tag],$result); //...Crea un array usando el valor existente y el nuevo
                }
            }

        } elseif($type == 'close') { //final del tag '</tag>'
            $current = &$parent[$level-1];
        }
    }

    return($xml_array);
}

?>

 

Thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.