1

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
  • Can you provide the code including your calls to the provided ArrayToXML::toXML()? Commented Oct 6, 2009 at 15:13

4 Answers 4

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

How? when i saw =null i thought it wasnt required
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?
0

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.

Comments

0

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

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.