Answers for "php simplexmlelement xml add attribute"

PHP
0

php simplexmlelement xml add attribute

<?php
  function array_to_xml( $data, &$xml_data ) {
        foreach( $data as $key => $value ) {
            if (!empty($value)) {
                if( is_array($value)) {
                    if (!empty($value["@attributes"])) {
                            $subnode = $xml_data->addChild($key, $value["@value"]);
                            foreach ($value["@attributes"] as $key1 => $val1) {
                                $subnode->addAttribute($key1, $val1);
                            }
                    } else if ($key == "@value") {
                        foreach ($value as $attr => $attrVal) {
                            $subnode = $xml_data->addChild("$attr", $attrVal);
                            array_to_xml($attrVal, $subnode);
                        }
                    } else {
                            if (!empty($value)) {
                                    $subnode = $xml_data->addChild($key);
                                    array_to_xml($value, $subnode);
                            }
                    }
                } else {
                        $xml_data->addChild("$key",$value);
                }
            }
        }
    }

$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

$arrXml = [
    "categories" => [
        'category' => [
            '@attributes' => [
                'id' => '123',
                'parent_id' => '12345'
            ],
            '@value' => 'Bikes'
        ]
    ],
    "properties" => [
        'property' => [
            'id' => '123',
            'categoryId' => '1',
            'name' => 'Color',
            'values' => [
                'value' => [
                    "id" => '1',
                    "name" => 'Black'
                ],
                'value' => [
                    "id" => '2',
                    "name" => 'White'
                ]
            ]
        ]
    ],
    "products" => [
        'products' => [
            'id' => '1231231',
            'categoryId' => '123',
            'model' => [
                    '@attributes' => [
                            'foo' => 'bar',
                    ],
                '@value' => 'Avalanche'
            ],
            'article' => '1.0 2011',
            'vendor' => 'GT',
        ]
    ]
];

array_to_xml($arrXml,$xml_data);

//saving generated xml file;
$result = $xml_data->asXML('test.xml');
Posted by: Guest on September-18-2021

Browse Popular Code Answers by Language