ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

PHP数组输出为xml的两种常见方法

2022-08-22 21:01:07  阅读:346  来源: 互联网

标签:xml XML doc 数组 array PHP root


很多时候,我们需要将数据以XML格式存储到数据库或文件中,以备后用。为了满足此需求,我们将需要将数据转换为XML并保存XML文件。在本教程中,我们将讨论如何使用PHP将数组转化为xml格式。

我们将使用以下2种方法来做到这一点。

  1. SimpleXMLElement类 
  2. DOMDocument()类

 

使用SimpleXMLElement类将数组转化为xml

SimpleXML扩展函数提供了将XML转换为对象的工具集。这些对象处理普通的属性选择器和数组迭代器。

下面的代码使用元素根创建一个xml对象。

$xml = new SimpleXMLElement('');

我们可以使用array_walk_recursive()函数将数组转换为XML文档,其中将数组的键转换为值,并将数组的值转换为XML元素。

例子:

<?php 
// Code to convert php array to xml document 
  
// Creating an array 
$my_array = array ( 
    'a' => 'x', 
    'b' => 'y', 
      
    // creating nested array 
    'another_array' => array ( 
        'c' => 'z', 
    ), 
); 
  
// This function create a xml object with element root. 
$xml = new SimpleXMLElement('<root/>'); 
  
// This function resursively added element 
// of array to xml document 
array_walk_recursive($my_array, array ($xml, 'addChild')); 
  
// This function prints xml document. 
print $xml->asXML(); 
?> 

输出:

<?xml version="1.0"? >
<root >
       <x> a </x >
       <y> b </y >
       <z> c </z >
</root >

 

使用DOMDocument()类将数组转化为xml

要使用DOMDocument创建XML,基本上,我们需要使用createElement()和 createAttribute() 方法创建标记和属性,使用appendChild()来创建XML结构 。

例子:

<?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>

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家

标签:xml,XML,doc,数组,array,PHP,root
来源: https://www.cnblogs.com/myhomepages/p/16614229.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有