0

This is my code,

 $row=array(username=>'username',password=>'password');
 $var=array_flip($row);
 $xml = new SimpleXMLElement('<root/>');
 array_walk_recursive($var, array ($xml, 'addChild'));
 $result= $xml->asXML();

If username and password are different say 'abcd' & 'efgh' respectively, xml looks like this:

<root>
<username>abcd</username>
<password>efgh</password>
</root>

but if they are same say 'abcd', xml looks like this:

<root>
<password>abcd</password>
</root>

and I want that it should show like

<root>
<username>abcd</username>
<password>abcd</password>
</root>

So how can I solve that?

3
  • if you see the xml generated, when username and password are same <username> node is not created in xml. How to solve that? Commented Nov 14, 2012 at 10:49
  • When you do array_flip duplicate keys are discarded. Commented Nov 14, 2012 at 10:50
  • but without array_flip() the xml will be like this <abcd>username</abcd>. Commented Nov 14, 2012 at 10:55

2 Answers 2

1

http://www.php.net/manual/en/function.array-flip.php

If a value has several occurrences, the latest key will be used as its values, and all others will be lost.

if password equals to username, then array_flip returns array with just one element

array_flip(array(username=>'abcd',password=>'abcd'))
// will return array('abcd'=>'password')

you cat use foreach instead of array_walk_recursive in this case

foreach ($row as $k => $v)
   $xml->addChild($k, $v);
Sign up to request clarification or add additional context in comments.

Comments

0

Try

array_walk_recursive($row, function ($value, $key) use ($xml) { 
    $xml->addChild($key, $value); 
  }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.