views:

137

answers:

4

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);
A: 

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

GSto
How? when i saw =null i thought it wasnt required
An employee
it says you are making a call on a non-object. That means the object does not exist. if it's null, how can it have a method?
GSto
+1  A: 

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();
cletus
A: 

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.

Citizen
A: 

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

Justin