D
D
Dmitry2020-02-03 17:49:57
PHP
Dmitry, 2020-02-03 17:49:57

How to generate array from xml?

Hello!
There is XML

<category categories_id="62">
     <categories_name>One</categories_name>
     <categories_id>62</categories_id>
     <parent_id>0</parent_id>
</category>
<category categories_id="652">
      <categories_name>Two</categories_name>
      <categories_id>652</categories_id>
      <parent_id>62</parent_id>
</category>
<category categories_id="581">
      <categories_name>Three</categories_name>
      <categories_id>581</categories_id>
      <parent_id>652</parent_id>
</category>
<category categories_id="581">
      <categories_name>Three</categories_name>
      <categories_id>581</categories_id>
      <parent_id>652</parent_id>
</category><category categories_id="63">
     <categories_name>One</categories_name>
     <categories_id>63</categories_id>
     <parent_id>0</parent_id>
</category>
<category categories_id="653">
      <categories_name>Two</categories_name>
      <categories_id>653</categories_id>
      <parent_id>63</parent_id>
</category>
<category categories_id="583">
      <categories_name>Three</categories_name>
      <categories_id>583</categories_id>
      <parent_id>653</parent_id>
</category>

To get
$a= [
'583'=>[
0=>'Three',
1=>'Two,
2=>'One'
],
'581'=>[
0=>'Three',
1= >'Two,
2=>'One'
],
];
The question is exactly how to collect an array of categories and subcategories, not how to process xml

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xenonhammer, 2020-02-03
@xenonhammer

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

json_decode($json,TRUE);
TRUE output yields an array that can be
iterated over foreach($data as $data_1){
foreach($data_1 as $data_2){
$data_2 = ($data_2[key][key][value]);
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question