0

I need to know how to store this data into one or two arrays with keys and export them into json format.

Here is the XML input, that I'm parsing:

<a id="12">
    <n>Usa</n>
<a id="28">
    <n>Maroko</n>
</a>
<a id="33">
    <n>Finland</n>
</a>
<a id="41">
    <n>Russia</n>
</a>

I haven't problem to parse this data, but how should I store this data into array with keys ("id", "country") and export into json with json_encode. I would like to get this output:

[
   {
      "id":"12",
      "country":"Usa"
   },
   {
      "id":"28",
      "country":"Maroko"
   },
   {
      "id":"33",
      "country":"Finland"
   },
   {
      "id":"41",
      "country":"Russia"
   }
]

I know, very simple, but I can't find the answer. Many thanks

user997777
  • 569
  • 1
  • 7
  • 19

1 Answers1

0

If you're happy with parsing the data from XML then to put data into an array in PHP just do it like this:

$data = []; // empty array
$data[] = array("id" => "12", "country" => "Usa"); // push new data array into array
$data[] = array("id" => "28", "country" => "Maroko");
$data[] = array("id" => "33", "country" => "Finland");
$data[] = array("id" => "41", "country" => "Russia");

Then to encode it into JSON:

$json = json_encode($data);

print $json;
Dean Jenkins
  • 194
  • 5