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

标签 php xml json

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

我搜索了很多,只能找到不输出有效 XML 的函数。我相信我正在测试它们的数组是正确构造的,因为它可以正确地用于使用 json_encode 生成 JSON 文档。但是,它相当大并且嵌套在四个层次上,这也许可以解释为什么我到目前为止尝试的功能都失败了。

最终,我将自己编写代码来生成 XML,但肯定有更快的方法来完成此操作。

最佳答案

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

经过大量的挫折和研究,​​这就是我想出来的

XML 关联。数组:

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

json_decode( json_encode( simplexml_load_string( $string ) ), TRUE );

副教授。数组到 XML

注释:

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

From 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;
    }
}

...这是用于$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

关于php - 在 PHP 中将关联数组转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733041/

相关文章:

arrays - 强制执行数组内容的 JSON 模式

json - row_to_json 给出带有小写字段名称的 JSON

php - 您的 SQL 语法有误;查看与您的 MariaDB 服务器版本对应的手册,了解使用 near 'range 的正确语法

php - 如何在android中以图形形式表示mysql数据库?

php - 在 Mediawiki 中上传时调整图像大小

php - 使用 PHP 进行非常大的上传

java - 将 XML 转换为 Java Map<String, Integer>

php - PHP INSERT 到 MySQL 数据库的问题

android - DataBinding 在自定义横向布局膨胀时失败

java - 通过 ID 检索数组的名称