0
votes

I do not understand these node value things at all i am trying to replicate an xml design in php but
having quite a bit of trouble the file i am trying to reproduce through php is.

   <items>
        <item>
              <id></id>
              <name></name>
              <price></price>
              <quantity></quantity>
              <description></description>
              <qonhold></qonhold>
              <qsold></qsold>
        </item>
     </items>

And the PHP file to recreate this is almost all done

  $dom = new DOMDocument("1.0");

  // create root element
  $root = $dom->createElement("Items");
  $dom->appendChild($root);
  $dom->formatOutput=true;

  // create child element
  $item = $dom->createElement("item");
  $dom->appendChild($item);

  // create text node
  $id = $dom->createElement("id");
  $root->appendChild($id);

  $name = $dom->createElement("name");
  $root->appendChild($name);


  $price = $dom->createElement("price");
  $root->appendChild($price);

  $quantity = $dom->createElement("quantity");
  $root->appendChild($quantity);

  $description = $dom->createElement("description");
  $root->appendChild($description);


  $qonhold = $dom->createElement("qonhold");
  $root->appendChild($qonhold);


  $qsold = $dom->createElement("qsold");
  $root->appendChild($qsold);

The problem i am having is its saving it all under "items" being the root.. but i can not get everything id, name, price, quantity, description, qonhold, qsold to save under just "item" which is saved under "items

1

1 Answers

2
votes

You should use ->appendChild() on the item node created, not the root which is <items>:

// create child element
$item = $dom->createElement("item");
$dom->appendChild($item);

// create text node
$id = $dom->createElement("id");
$item->appendChild($id); // item->appendChild not $root->appendChild

Should look like this:

$dom = new DOMDocument("1.0");

// create root element
$root = $dom->createElement("Items");
$dom->appendChild($root);
$dom->formatOutput=true;

// create child element
$item = $dom->createElement("item");
$root->appendChild($item); // append to `<Items>`

// create text node
$id = $dom->createElement("id");
$item->appendChild($id); // append to `<item>`

$name = $dom->createElement("name");
$item->appendChild($name); // append to `<item>`


$price = $dom->createElement("price");
$item->appendChild($price); // append to `<item>`

$quantity = $dom->createElement("quantity");
$item->appendChild($quantity); // append to `<item>`

$description = $dom->createElement("description");
$item->appendChild($description); // append to `<item>`


$qonhold = $dom->createElement("qonhold");
$item->appendChild($qonhold); // append to `<item>`


$qsold = $dom->createElement("qsold");
$item->appendChild($qsold); // append to `<item>`