简体   繁体   中英

how to convert php array to xml

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>

try like this.

   $xml = new SimpleXMLElement('<note/>');
   $row = array_flip($row);
   array_walk_recursive($row, array ($xml, 'addChild'));
   echo htmlentities($xml->asXML());

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>

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