convert associate array to XML in php

旧巷老猫 提交于 2019-12-11 04:54:30

问题


How do i convert an associate array to an XML string? I found this but get the error 'Call to a member function addChild() on a non-object' when running the line

$node = $xml->addChild($key);

回答1:


Use the PHP Document Object Model:

$xml = new DOMDocument('1.0', 'utf-8');
$root = $xml->createElement('top');
$xml->appendChild($root);
foreach ($arr as $k => $v) {
  $node = $xml->createelement($k);
  $text = $xml->createTextNode($v);
  $node->appendChild($text);
  $root->appendChild($node);
}
echo $xml->saveXml();



回答2:


Did you initialize the $xml object? That's probably your problem.




回答3:


Its pretty similar to how you would do something like this:

while($row = mysql_fetch_assoc($result))

You can't use $result as an array, but you can foreach or while through the different entries.




回答4:


PEAR's XML_Serialize is pretty good if you want a easy solution. Doing the DOM manually is arguably faster.



来源:https://stackoverflow.com/questions/1526215/convert-associate-array-to-xml-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!