簡體   English   中英

在PHP中將關聯數組轉換為XML

[英]Convert associative array to XML in PHP

我想知道在PHP(或一些廣泛使用的PHP庫)中是否存在能夠將關聯數組轉換為XML文檔的函數。

我搜索了很多,只能找到不輸出有效XML的函數。 我相信我正在測試它們的數組是正確構造的,因為它可以正確地用於使用json_encode生成JSON文檔。 但是,它相當大,它嵌套在四個級別,這可以解釋為什么我迄今為止嘗試過的函數都失敗了。

最后,我將編寫代碼來自己生成XML,但肯定必須有更快的方法來實現這一點。

我在這里意識到我是一個Johnny-Come-Lately,但我正在處理非常相同的問題 - 我在那里找到的教程幾乎 (但不完全在單元測試中)覆蓋它。

在經歷了許多挫折和研究之后,這就是我所追求的

XML到Assoc。 陣:

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

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

協會。 數組到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;
    }
}

...這里是用於$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數組 - > JSON工作得很好,因為那些結構......好吧......幾乎一樣。

呼叫

// $data = array(...);
$dataTransformator = new DataTransformator();
$domDocument = $dataTransformator->data2domDocument($data);
$xml = $domDocument->saveXML();

DataTransformator

class DataTransformator {

    /**
     * Converts the $data to a \DOMDocument.
     * @param array $data
     * @param string $rootElementName
     * @param string $defaultElementName
     * @see MyNamespace\Dom\DataTransformator#data2domNode(...)
     * @return Ambigous <DOMDocument>
     */
    public function data2domDocument(array $data, $rootElementName = 'data', $defaultElementName = 'item') {
        return $this->data2domNode($data, $rootElementName, null, $defaultElementName);
    }

    /**
     * Converts the $data to a \DOMNode.
     * If the $elementContent is a string,
     * a DOMNode with a nested shallow DOMElement
     * will be (created if the argument $node is null and) returned.
     * If the $elementContent is an array,
     * the function will applied on every its element recursively and
     * a DOMNode with a nested DOMElements
     * will be (created if the argument $node is null and) returned.
     * The end result is always a DOMDocument object.
     * The casue is, that a \DOMElement object
     * "is read only. It may be appended to a document,
     * but additional nodes may not be appended to this node
     * until the node is associated with a document."
     * See {@link http://php.net/manual/en/domelement.construct.php here}).
     * 
     * @param Ambigous <string, mixed> $elementName Used as element tagname. If it's not a string $defaultElementName is used instead.
     * @param Ambigous <string, array> $elementContent
     * @param Ambigous <\DOMDocument, NULL, \DOMElement> $parentNode The parent node is
     *  either a \DOMDocument (by the method calls from outside of the method)
     *  or a \DOMElement or NULL (by the calls from inside).
     *  Once again: For the calls from outside of the method the argument MUST be either a \DOMDocument object or NULL.
     * @param string $defaultElementName If the key of the array element is a string, it determines the DOM element name / tagname.
     *  For numeric indexes the $defaultElementName is used.
     * @return \DOMDocument
     */
    protected function data2domNode($elementContent, $elementName, \DOMNode $parentNode = null, $defaultElementName = 'item') {
        $parentNode = is_null($parentNode) ? new \DOMDocument('1.0', 'utf-8') : $parentNode;
        $name = is_string($elementName) ? $elementName : $defaultElementName;
        if (!is_array($elementContent)) {
            $content = htmlspecialchars($elementContent);
            $element = new \DOMElement($name, $content);
            $parentNode->appendChild($element);
        } else {
            $element = new \DOMElement($name);
            $parentNode->appendChild($element);
            foreach ($elementContent as $key => $value) {
                $elementChild = $this->data2domNode($value, $key, $element);
                $parentNode->appendChild($elementChild);
            }
        }
        return $parentNode;
    }
}

PHP的DOMDocument對象可能就是你要找的東西。 以下是使用此類將多維數組轉換為xml文件的示例鏈接 - http://www.php.net/manual/en/book.dom.php#78941

我需要一個能夠轉換具有非關聯子數組和內容的數組的解決方案,需要使用CDATA(<>&)進行轉義。 由於我找不到任何合適的解決方案,我基於SimpleXML實現了自己的解決方案,這應該非常快。

https://github.com/traeger/SimplestXML (此解決方案支持(關聯)數組=> XML和XML =>(關聯)數組轉換,無需屬性支持)。 我希望這可以幫助別人。

function combArrToXML($arrC=array(), $root="root", $element="element"){
  $doc = new DOMDocument();
  $doc->formatOutput = true;

  $r = $doc->createElement( $root );
  $doc->appendChild( $r );

  $b = $doc->createElement( $element );
  foreach( $arrC as  $key => $val)
  {
    $$key = $doc->createElement( $key );
    $$key->appendChild(
      $doc->createTextNode( $val )
    );
    $b->appendChild( $$key );
    $r->appendChild( $b );
  }

  return $doc->saveXML();
}

例:

$b=array("testa"=>"testb", "testc"=>"testd");
combArrToXML($b, "root", "element");

輸出:

<?xml version="1.0"?>
<root>
  <element>
    <testa>testb</testa>
    <testc>testd</testc>
  </element>
</root>

肯定必須有一個更快的方法來做到這一點

如果你已經安裝了PEAR,那就有了。 一下XML_Seralizer 這是測試版,所以你必須使用它

 pear install XML_Serializer-beta

安裝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM