我想在php中创建XML文件,并将值从数组保存到变量
<?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');
?>
我希望我的XML格式化这个
<?xml version="1.0"?>
<StudentDetails>
<StudentName>Pravin Parayan</StudentName>
<FatherEmailId>pravinp@pigtailpundits.com</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
<StudentDetails/>
但不是上面的我得到了一些喜欢这个
<?xml version="1.0"?>
<StudentDetails/>
<StudentName>Joel George</StudentName>
<FatherEmailId>joy@pigtailpundits.com</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
答案 0 :(得分:1)
您需要做的就是添加一个根元素StudentDetails,并附加所有其他元素,如下所示:
<?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');
结果如下:
<?xml version="1.0"?>
<StudentDetails>
<StudentName>Pravin Parayan</StudentName>
<FatherEmailId>pravinp@pigtailpundits.com</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
</StudentDetails>