Stefan Ayres Quinn
Stefan Ayres Quinn

Reputation: 33

Extract certain values from XML response to create custom JSON array

Hi Sorry if this is a silly question but I would appreciate any help getting pointed in the right direction. I have two API's I am using, the first one returns XML with what i need plus more. The second API takes a JSON object. What i am stuck on is getting the values i need out of the XML response and making the JSON object. At the moment i have this XML:

  <?xml version="1.0" encoding="UTF-8"?>
<wapi>
   <reply status="0" error_str="" error_code="0">
      <item>
         <firstname>Jim</firstname>
         <lastname>Doe</lastname>
         <accountnum>10037529</accountnum>
         <contact_number>353123451234</contact_number>
      </item>
      <item>
         <firstname>Jack</firstname>
         <lastname>Doe</lastname>
         <accountnum>10037530</accountnum>
         <contact_number>353123452345</contact_number>
      </item>
   </reply>
</wapi>

And I would like to get all instaces of the "accountnum" value and inserting it into a JSON object like the below with a static key called "customer-id", this JSON will then be sent to the second API.

[
  {
    "customer-id": "10037529"
  },
  {
    "customer-id": "10037530"
  }
]

I am using PHP to do this and i have tried json_encode to change to JSON and then parse it but I couldn't get that to work i also turned it into an array and looped over it but couldn't get the value out. I am only writing here as i have searched for hours and cant seem to find anything close to what i am doing, or maybe im just going about this wrong.

Again any pointers would be great, thanks.

Upvotes: 2

Views: 58

Answers (1)

Dark Knight
Dark Knight

Reputation: 6531

Consider you have your xml in $str variable.

$xml  = simplexml_load_string ($str);
$data = [];
foreach ($xml->reply->item as $item) { 
    $data[] = ['customer-id' => (string)$item->accountnum];
}

echo json_encode($data);
Output:
[{"customer-id":"10037529"},{"customer-id":"10037530"}]

Upvotes: 2

Related Questions