[英]Create XML file in php using DOMDocument()
我想在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>
您需要做的就是添加根元素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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.