0

I have php array like below

$row = array (
  'name' => 'david',
 'bio' => 'good man'
 );

i want to convert this array to corresponding XML page like scenario below.

 <?xml version="1.0" encoding="UTF-8"?>
 <note>
   <name>david</name>
   <bio>good man</bio>
</note>
3
  • What have you tried so far? Have you looked up methods of creating XML using PHP? Commented Sep 11, 2014 at 13:11
  • i want to the php array get output like <note> <name>david</name> <bio>good man</bio> </note> Commented Sep 11, 2014 at 13:15
  • I think this answer will make your life easier :D http://stackoverflow.com/a/5965940/2178259 Commented Sep 11, 2014 at 13:38

2 Answers 2

1

try like this.

   $xml = new SimpleXMLElement('<note/>');
   $row = array_flip($row);
   array_walk_recursive($row, array ($xml, 'addChild'));
   echo htmlentities($xml->asXML());
Sign up to request clarification or add additional context in comments.

8 Comments

use echo htmlentities($xml->asXML()); to see the markup, this is the correct answer, +1
<?xml version="1.0"?> <root><blub>bla</blub><bar>foo</bar></root> but can i get it in output like this.
thabk you Ghost. Its Working
thanks, Ghost for your help. I am updating this answer as well
hi ghost are you there
|
0

Generate XML with DOM:

$row = array (
  'name' => 'david',
  'bio' => 'good man'
);

$dom = new DOMDocument();
$dom->formatOutput = TRUE;

$note = $dom->appendChild($dom->createElement('note'));
foreach ($row as $name => $value) {
  $note
    ->appendChild($dom->createElement($name))
    ->appendChild($dom->createTextNode($value));
}

echo $dom->saveXml(); 

Output:

<?xml version="1.0"?>
<note>
  <name>david</name>
  <bio>good man</bio>
</note>

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.