PHP数组输出为xml的两种常见方法
2022/8/23 1:52:53
本文主要是介绍PHP数组输出为xml的两种常见方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
很多时候,我们需要将数据以XML格式存储到数据库或文件中,以备后用。为了满足此需求,我们将需要将数据转换为XML并保存XML文件。在本教程中,我们将讨论如何使用PHP将数组转化为xml格式。
我们将使用以下2种方法来做到这一点。
- SimpleXMLElement类
- 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>
以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
这篇关于PHP数组输出为xml的两种常见方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-29env: php: no such file or directory
- 2024-03-01php foreach break
- 2024-02-26Exception参数 php-icode9专业技术文章分享
- 2023-12-30PHP文件批量上传-icode9专业技术文章分享
- 2023-12-30thinkphp6 withJoin-icode9专业技术文章分享
- 2023-12-27MagicArray:像php一样,让Go业务代码不再卷!
- 2023-11-18centos7编译安装PHP教程。
- 2023-11-18centos7编译安装phpMyAdmin教程。
- 2023-10-13唱衰这么多年,PHP 仍然还是你大爷!
- 2023-07-25PHP8,性能更好,语法更好,类型安全更完善