简体   繁体   中英

Generate XML file in PHP

I am trying to generate the XML file from the PHP array. Everything seems working quite well, but I cannot remove the parent node.

This is how my array looks like:

这是我的数组的样子:

And this is the generated XML file

在此处输入图片说明

As you can see I have some "items" inside the parent node named "item".

I just want to know, how I can remove the parent node named "item" and leave just structure like:

在此处输入图片说明

My PHP code:

    function array_to_xml( $data, $xml_data ) {
        foreach( $data as $key => $value ) {
            if( is_numeric($key) ){
                $key = 'item';
            }
            if( is_array($value) ) {
                $subnode = $xml_data->addChild($key);
                array_to_xml($value, $subnode);
            } else {
                $xml_data->addChild("$key",htmlspecialchars("$value"));
            }
         }
    }

    $xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

    array_to_xml($newArrayXml,$xml_data);

    //saving generated xml file; 
    $result = $xml_data->asXML('list.xml')

When I ran the above code using the following array, it output what you are looking for:

$newArrayXml = array(
 2410687 => array('id' => 2410687),
 2440673 => array('id' => 2440673),
 2415709 => array('id' => 2415709),
 2445675 => array('id' => 2445675)
);

// var_dump($newArrayXml);exit;

function array_to_xml( $data, $xml_data ) {
 foreach( $data as $key => $value ) {
  if( is_numeric($key) ){
   $key = 'item';
  }
  if( is_array($value) ) {
   $subnode = $xml_data->addChild($key);
   array_to_xml($value, $subnode);
  } else {
   $xml_data->addChild("$key",htmlspecialchars("$value"));
  }
 }
}

$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

array_to_xml($newArrayXml,$xml_data);

//saving generated xml file;
$result = $xml_data->asXML('list.xml');

Result:

<?xml version="1.0"?>
<data>
<item><id>2410687</id></item>
<item><id>2440673</id></item>
<item><id>2415709</id></item>
<item><id>2445675</id></item>
</data>

Perhaps the issue is with your array. It shows array(1) in your photo, which would imply you have an extra array:

$newArrayXml = array(array(
 2410687 => array('id' => 2410687),
 2440673 => array('id' => 2440673),
 2415709 => array('id' => 2415709),
 2445675 => array('id' => 2445675)
));

This generates the output that you did not want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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