simplexmlelement add attribute

Solutions on MaxInterview for simplexmlelement add attribute by the best coders in the world

showing results for - "simplexmlelement add attribute"
Darrell
15 Aug 2018
1<?php
2  function array_to_xml( $data, &$xml_data ) {
3        foreach( $data as $key => $value ) {
4            if (!empty($value)) {
5                if( is_array($value)) {
6                    if (!empty($value["@attributes"])) {
7                            $subnode = $xml_data->addChild($key, $value["@value"]);
8                            foreach ($value["@attributes"] as $key1 => $val1) {
9                                $subnode->addAttribute($key1, $val1);
10                            }
11                    } else if ($key == "@value") {
12                        foreach ($value as $attr => $attrVal) {
13                            $subnode = $xml_data->addChild("$attr", $attrVal);
14                            array_to_xml($attrVal, $subnode);
15                        }
16                    } else {
17                            if (!empty($value)) {
18                                    $subnode = $xml_data->addChild($key);
19                                    array_to_xml($value, $subnode);
20                            }
21                    }
22                } else {
23                        $xml_data->addChild("$key",$value);
24                }
25            }
26        }
27    }
28
29$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
30
31$arrXml = [
32    "categories" => [
33        'category' => [
34            '@attributes' => [
35                'id' => '123',
36                'parent_id' => '12345'
37            ],
38            '@value' => 'Bikes'
39        ]
40    ],
41    "properties" => [
42        'property' => [
43            'id' => '123',
44            'categoryId' => '1',
45            'name' => 'Color',
46            'values' => [
47                'value' => [
48                    "id" => '1',
49                    "name" => 'Black'
50                ],
51                'value' => [
52                    "id" => '2',
53                    "name" => 'White'
54                ]
55            ]
56        ]
57    ],
58    "products" => [
59        'products' => [
60            'id' => '1231231',
61            'categoryId' => '123',
62            'model' => [
63                    '@attributes' => [
64                            'foo' => 'bar',
65                    ],
66                '@value' => 'Avalanche'
67            ],
68            'article' => '1.0 2011',
69            'vendor' => 'GT',
70        ]
71    ]
72];
73
74array_to_xml($arrXml,$xml_data);
75
76//saving generated xml file;
77$result = $xml_data->asXML('test.xml');