douguanya6399 2016-11-19 07:01
浏览 47
已采纳

使用DOMDocument()在php中创建XML文件

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>pravinp@pigtailpundits.com</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>joy@pigtailpundits.com</FatherEmailId>
<PhoneNumber>9000012345</PhoneNumber>
  • 写回答

1条回答 默认 最新

  • dongzouqie4220 2016-11-19 09:01
    关注

    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>pravinp@pigtailpundits.com</FatherEmailId>
      <PhoneNumber>9000012345</PhoneNumber>
    </StudentDetails>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法