在PHP中将关联数组转换为XML

Epi*_*rus 10 php xml json

我想知道在PHP(或一些广泛使用的PHP库)中是否存在能够将关联数组转换为XML文档的函数.

我搜索了很多,只能找到不输出有效XML的函数.我相信我正在测试它们的数组是正确构造的,因为它可以正确地用于使用json_encode生成JSON文档.但是,它相当大,它嵌套在四个级别,这可以解释为什么我迄今为止尝试过的函数都失败了.

最后,我将编写代码来自己生成XML,但肯定必须有更快的方法来实现这一点.

小智 7

我在这里意识到我是一个Johnny-Come-Lately,但我正在处理非常相同的问题 - 我在那里找到的教程几乎(但不完全在单元测试中)覆盖它.

在经历了许多挫折和研究之后,这就是我所追求的

XML到Assoc.阵:

来自http://www.php.net/manual/en/simplexml.examples-basic.php

json_decode( json_encode( simplexml_load_string( $string ) ), TRUE );
Run Code Online (Sandbox Code Playgroud)

协会.数组到XML

笔记:

  • 不处理XML属性
  • 处理与数字索引嵌套的数组(这是不是有效的XML!)

来自http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/

/// Converts an array to XML
/// - http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
/// @param  <array> $array  The associative array you want to convert; nested numeric indices are OK!
function   getXml( array $array )  {

    $array2XmlConverter  = new XmlDomConstructor('1.0', 'utf-8');
    $array2XmlConverter->xmlStandalone   = TRUE;
    $array2XmlConverter->formatOutput    = TRUE;

    try {
        $array2XmlConverter->fromMixed( $array );
        $array2XmlConverter->normalizeDocument ();
        $xml    = $array2XmlConverter->saveXML();
//        echo "\n\n-----vvv start returned xml vvv-----\n";
//        print_r( $xml );
//        echo "\n------^^^ end returned xml ^^^----\n"
        return  $xml;
    }
    catch( Exception $ex )  {
//        echo "\n\n-----vvv Rut-roh Raggy! vvv-----\n";
//        print_r( $ex->getCode() );     echo "\n";
//        print_r( $->getMessage() );
//        var_dump( $ex );
//        echo "\n------^^^ end Rut-roh Raggy! ^^^----\n"
        return  $ex;
    }
}
Run Code Online (Sandbox Code Playgroud)

...这里是用于$array2XmlConverter对象的类:

/**
 * Extends the DOMDocument to implement personal (utility) methods.
 * - From: http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
 * - `parent::` See http://www.php.net/manual/en/class.domdocument.php
 *
 * @throws   DOMException   http://www.php.net/manual/en/class.domexception.php
 *
 * @author Toni Van de Voorde
 */
class   XmlDomConstructor   extends DOMDocument {

    /**
     * Constructs elements and texts from an array or string.
     * The array can contain an element's name in the index part
     * and an element's text in the value part.
     *
     * It can also creates an xml with the same element tagName on the same
     * level.
     *
     * ex:
        \verbatim
             <nodes>
                <node>text</node>
                <node>
                    <field>hello</field>
                    <field>world</field>
                </node>
             </nodes>
        \verbatim
     *
     *
     * Array should then look like:
        \verbatim
             array(
                "nodes" => array(
                    "node" => array(
                        0 => "text",
                        1 => array(
                            "field" => array (
                                0 => "hello",
                                1 => "world",
                            ),
                        ),
                    ),
                ),
             );
        \endverbatim
     *
     * @param mixed $mixed An array or string.
     *
     * @param DOMElement[optional] $domElement Then element
     * from where the array will be construct to.
     *
     */
    public  function    fromMixed($mixed, DOMElement $domElement = null) {

        $domElement = is_null($domElement) ? $this : $domElement;

        if (is_array($mixed)) {
            foreach( $mixed as $index => $mixedElement ) {

                if ( is_int($index) ) {
                    if ( $index == 0 ) {
                        $node = $domElement;
                    } 
                    else {
                        $node = $this->createElement($domElement->tagName);
                        $domElement->parentNode->appendChild($node);
                    }
                }
                else {
                    $node = $this->createElement($index);
                    $domElement->appendChild($node);
                }

                $this->fromMixed($mixedElement, $node);
            }
        } 
        else {
            $domElement->appendChild($this->createTextNode($mixed));
        }
    }
} // end of class
Run Code Online (Sandbox Code Playgroud)


Nem*_*den 5

不,至少没有这样的内置功能.写它根本不是一个问题.

肯定必须有一个更快的方法来做到这一点

你如何表示数组中的属性?我可以假设键是标签,值是这个标签的内容.

基本的PHP数组 - > JSON工作正常,因为那些结构......好吧......几乎一样.

  • JSON对象和PHP数组在性质上非常相似; XML是一个完全不同的动物,主要是因为(a)属性 - 值 - 和(b)具有相同名称的多个节点(即数字索引数组,但那么如何选择名称?); 就个人而言,我认为您不能在项目/应用范围之上制定一个通用的解决方案. (2认同)