Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

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

 Share


HACK1949

Recommended Posts

很多时候,我们需要将数据以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>

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

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...