0

I want to create XML file in php and I have saved the values from array to variable

<?php
$name = $e['name_1'];
$email = $e['email_id'];
$phone_no =$e['phone_no'];

$doc = new DOMDocument();
$doc->formatOutput = true;

$ele1 = $doc->createElement('StudentName');
$ele1->nodeValue=$name;
$doc->appendChild($ele1);

$ele2 = $doc->createElement('FatherEmailId');
$ele2->nodeValue=$email;
$doc->appendChild($ele2);

$ele3 = $doc->createElement('PhoneNumber');
$ele3->nodeValue=$phone_no;
$doc->appendChild($ele3);

$doc->save('MyXmlFile007.xml');  

?>

i want my XML formatted lik this

<?xml version="1.0"?>
<StudentDetails>
<StudentName>Pravin Parayan</StudentName>
<FatherEmailId>[email protected]</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
<StudentDetails/>

But instead of the above i get something lik this

<?xml version="1.0"?>
<StudentDetails/>
<StudentName>Joel George</StudentName>
<FatherEmailId>[email protected]</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
4
  • Can you share your data array, which you used to create xml document Commented Nov 19, 2016 at 7:04
  • I misplaced the data inside the XML file format. Commented Nov 19, 2016 at 7:04
  • $e = array('name_1' =>'Joel' , 'email_id' =>'[email protected]','phone_no' => '9000012345' ); @user3099298 Commented Nov 19, 2016 at 7:07
  • I have sorted out the database to fetch the last in data for the purpose Commented Nov 19, 2016 at 7:08

1 Answer 1

3

All you need to do is to add a root element StudentDetails, and append all other elements ti it, like the following:

<?php
$name = $e['name_1'];
$email = $e['email_id'];
$phone_no =$e['phone_no'];

$doc = new DOMDocument();
$doc->formatOutput = true;

$root = $doc->createElement('StudentDetails');
$root = $doc->appendChild($root);

$ele1 = $doc->createElement('StudentName');
$ele1->nodeValue=$name;
$root->appendChild($ele1);

$ele2 = $doc->createElement('FatherEmailId');
$ele2->nodeValue=$email;
$root->appendChild($ele2);

$ele3 = $doc->createElement('PhoneNumber');
$ele3->nodeValue=$phone_no;
$root->appendChild($ele3);

$doc->save('MyXmlFile007.xml');

And the result would be like:

<?xml version="1.0"?>
<StudentDetails>
  <StudentName>Pravin Parayan</StudentName>
  <FatherEmailId>[email protected]</FatherEmailId>
  <PhoneNumber>9000012345</PhoneNumber>
</StudentDetails>
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.