1

I have an array

$arr=array("A","B","C");

and I want to create a multi level XML from that like

<root>
  <error>
    <A>
      <B>
        <C>
          <D/>
        </C>
      </B>
    </A>
  </error>
</root>

and I have written the code as

$arr = array("A", "B", "C", "D");
$doc = new DomDocument();
$doc->formatOutput=true;
$doc->LoadXML('<root/>');
$root = $doc->documentElement;
$errorgroup = $doc->createElement('error');
$root->appendChild($errorgroup);
foreach($arr as $erreur) {
    $missinggroup = $doc->createElement($erreur);
    $errorgroup->appendChild($missinggroup);
    $errorgroup=$doc->createElement($erreur);
}
echo $doc->saveXml();

but the output is only displaying <A/> in the XML inside error and not the rest B and C. Where am I going wrong here?

1 Answer 1

1

Hope this one will be helpful.

Problem: $errorgroup=$doc->createElement($erreur); I don't what you were trying to do with this line.

Change this:

$errorgroup=$doc->createElement($erreur);

To this:

$errorgroup=$missinggroup;

Try this code snippet here

<?php

ini_set('display_errors', 1);

$arr = array("A", "B", "C", "D");
$doc = new DomDocument();
$doc->formatOutput=true;
$doc->LoadXML('<root/>');
$root = $doc->documentElement;
$errorgroup = $doc->createElement('error');
$root->appendChild($errorgroup);
foreach($arr as $erreur) {
    $missinggroup = $doc->createElement($erreur);
    $errorgroup->appendChild($missinggroup);
    $errorgroup=$missinggroup;
}
echo $doc->saveXml();

Output:

<root>
  <error>
    <A>
      <B>
        <C>
          <D/>
        </C>
      </B>
    </A>
  </error>
</root>
Sign up to request clarification or add additional context in comments.

3 Comments

@timukh Hope this one will be helpful.
Yes it is working! Thank you so much. I see where I went wrong now. Thanks again!
Yes I will, but there is a minimum time and before that the site is not letting me accept an answer. It is showing "you can accept an answer in 5 minutes". So I will after 5mins :)

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.