1

i am facing a problem in updating my XML using PHP & DOM.My XML file is in this format:

Original XML (& desired xml layout):

<?xml version="1.0" standalone="yes"?>
<Rows>
  <Row CustomerAccountNumber="COU002" />
  <Row CustomerAccountNumber="COU023" />
  <Row CustomerAccountNumber="C2335" />
  <Row CustomerAccountNumber="CvbU002" />

And the code that saves i.e adds the new record to the XML(customer.xml) is:

<?php

$xmldoc=new DOMDocument();
$xmldoc->load('XML/customer.xml');

$newAct= 'c12345';

$root = $xmldoc->firstChild;

$newElement= $xmldoc->createElement('CustomerAccountNumber');
$root->appendChild($newElement);
$newText= $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);

$xmldoc->save('XML/customer.xml');
 ?>

Issue : The Code is generating the new record in this format:

  <Rows>
  <Row CustomerAccountNumber="COU002" />
  <Row CustomerAccountNumber="COU023" />
  <Row CustomerAccountNumber="C2335" />
  <Row CustomerAccountNumber="CvbU002" />
  <CustomerAccountNumber>c12345</CustomerAccountNumber>

</Rows>

I couldn't understand where i am making mistake.All i want to retain my original XML format.I want output file in the above mentioned original format(See top).Kindly guide me and point me where i am making mistake that is generating incorrect format within the file itself.Plz help

1 Answer 1

1

Your issue is that you are currently creating a new CustomerAccountNumber element. Instead, you want to create a new Row element, and then create a new CustomerAccountNumber attribute:

$newElement = $xmldoc->createElement('Row');
$newAttribute = $xmldoc->createAttribute('CustomerAccountNumber');
$newAttribute->value = $newAct;
$newElement->appendChild($newAttribute);
$root->appendChild($newElement);
Sign up to request clarification or add additional context in comments.

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.