How to convert array to SimpleXML

前端 未结 30 2576
遇见更好的自我
遇见更好的自我 2020-11-21 06:52

How can I convert an array to a SimpleXML object in PHP?

30条回答
  •  旧巷少年郎
    2020-11-21 07:23

    The answers provided here only convert array to XML with nodes, you are not able to set attributes. I have written a php function that allows you to convert an array to php and also set attributes for particular nodes in the xml. The downside here is you have to construct an array in a particular way with few conventions (only if you want to use attributes)

    The following example will allow you to set attributes in XML too.

    The source can be found here: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php

     array(
            'type' => 'fiction'
        ),
        'book' => array(
            array(
                '@attributes' => array(
                    'author' => 'George Orwell'
                ),
                'title' => '1984'
            ),
            array(
                '@attributes' => array(
                    'author' => 'Isaac Asimov'
                ),
                'title' => 'Foundation',
                'price' => '$15.61'
            ),
            array(
                '@attributes' => array(
                    'author' => 'Robert A Heinlein'
                ),
                'title' => 'Stranger in a Strange Land',
                'price' => array(
                    '@attributes' => array(
                        'discount' => '10%'
                    ),
                    '@value' => '$18.00'
                )
            )
        )
    );
    /* creates 
    
      
        1984
      
      
        Foundation
        $15.61
      
      
        Stranger in a Strange Land
        $18.00
      
    
    */
    ?>
    

提交回复
热议问题