简体   繁体   中英

XML node and values reversed using SimpleXMLElement and array_walk()

I am trying to build an XML element from an array in PHP using an example that was posted elsewhere on this site. The XML string is being created as expected however the nodes and their values are reversed. For Example:

$params = array(
        "email" => 'me@gmail.com'
        ,"pass" => '123456'
        ,"pass-conf" => '123456'
    );
    $xml = new SimpleXMLElement('<root/>');
    array_walk_recursive($params, array($xml, 'addChild'));
    echo $xml->asXML();

Now what I am expecting to be returned is:

<?xml version="1.0"?>
  <root>
    <email>me@gmail.com</email>
    <pass>123456</pass>
    <pass-conf>123456</pass-conf>
  </root>

However, what I keep getting is the node names as values and values as node names:

<?xml version="1.0"?>
  <root>
    <me@gmail.com>email</me@gmail.com>
    <123456>pass</123456>
    <123456>pass-conf</123456>
  </root>

I have tested switching the key with the value in the $params array, but that seems like a lazy hack to me. I believe the issue lies within my callback in array_walk_recursive , but I'm not sure how exactly to make it work. I am open to recommendations on better ways to convert a PHP array to XML. I just tried this because it seemed simple and not convoluted. (haha..)

The problem with your code is that array_walk_recursive supplies the callback with the arguments value then key (in that order).

SimpleXMLElement::addChild accepts the arguments name then value (in that order).


Here's a less convoluted solution

foreach ($params as $key => $value) {
    $xml->addChild($key, $value);
}

https://3v4l.org/oOHSb

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