简体   繁体   English

将php数组转换为xml

[英]Convert php array to xml

please review my code, i have tried several suggestion on various threads, i either get a blank out put or a string. 请查看我的代码,我在各种线程上尝试了几种建议,我要么输出为空,要么为字符串。

my code 我的密码

   <?php
       $input_array = array (
         'name' => 'John Doe',
         'course' => 'Computer Science',
         'age' => 'twenty one'
        );
       $xml = new SimpleXMLElement('<root/>');
       array_walk_recursive(array_flip($input_array), array ($xml, 'addChild'));
       print $xml->asXML();
    ?>

output John DoeComputer Sciencetwenty one 输出 John Doe计算机科学二十一

The web browser is parsing the tags which is why they appear to not be there. 网络浏览器正在解析标签,这就是它们似乎不存在的原因。

Right click and view source. 右键单击并查看源。 Or surround the output with <pre> tags. 或用<pre>标签包围输出。

print '<pre>';
print $xml->asXML();
print '</pre>';

This should work for you: 这应该为您工作:

<?php

    $input_array = array (
                   'name' => 'John Doe',
                   'course' => 'Computer Science',
                   'age' => 'twenty one'
                  );

    $xml = new SimpleXMLElement('<root/>');
    $arr = array_flip($input_array);
    array_walk_recursive($arr, array( $xml, 'addChild'));
                       //^^^ Can't use array_filp directly otherwise: Strict Standards: Only variables should be passed by reference

    print $xml->asXML();

?>

To get a nice formatted output you could do this: 要获得良好的格式化输出,可以执行以下操作:

header('Content-type: text/xml');

Output: 输出:

<root>
  <name>John Doe</name>
  <course>Computer Science</course>
  <age>twenty one</age>
</root>

a short one: 一个简短的:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in 结果是

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

For converting php array to xml refer this doc in that very good solution available 要将php数组转换为xml,请在可用的非常好的解决方案中参考此文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM