0
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <GetCategoriesJsonResponse xmlns="http://tempuri.org/">
        <GetCategoriesJsonResult>[{"code":"0","description":"Sides","storeNumber":"3733"},{"code":"1","description":"Sandwiches","storeNumber":"3733"},</GetCategoriesJsonResult>
        </GetCategoriesJsonResponse>
    </s:Body>
</s:Envelope>

That is the result of the API, but I want to convert it like:

[
    {
        "code": "0",
        "description": "Sides",
        "storeNumber": "3733"
    },
    {
        "code": "1",
        "description": "Sandwiches",
        "storeNumber": "3733"
    },
]

How can I do this? I've tried json_encode and json_decode but it didn't work for me. I have applied different methods to convert it but it's still showing XML results. Can anyone tell me how I can convert it into JSON?

omukiguy
  • 1,401
  • 3
  • 17
  • 36

3 Answers3

2

Here's a good answer on available options to working with xml https://stackoverflow.com/a/3577662/3266626

I use FluentDom

$xml = file_get_contents("xml_file.xml");
$doc = new DOMDocument();
$doc->loadXML($xml);
$json = new \FluentDOM\Serializer\Json\RabbitFish($doc);
$object = json_decode($json);

echo "<pre>" . print_r( $object, true) . "</pre>";
echo "<script>console.log({$json})</script>";

Edit: replaced

// PHP Deprecated: Non-static method DOMDocument::loadXML() should not be called statically
$doc = DOMDocument::loadXML($xml);

with

$doc = new DOMDocument();
$doc->loadXML($xml);
fbg13
  • 156
  • 1
  • 14
  • Have you tried the code? `new \FluentDOM\Serializer\Json\RabbitFish($doc)` returns a json object. – fbg13 Sep 28 '17 at 17:58
  • yes but

    Type: Error

    Message: Class 'FluentDOM\Serializer\Json\RabbitFish' not found

    Filename: /var/www/html/application/views/backend/add_veggies.php

    Line Number: 153

    – Bilal ahmad Khan Sep 28 '17 at 18:05
  • 1
    You have to include FluentDom in your project. – fbg13 Sep 28 '17 at 18:10
2

I found the solution on that link thanks guys for helping using api response in this way helps me alot How to convert SOAP response to PHP Array?

$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//sBody')[0];
$array = json_decode(json_encode((array)$body), TRUE);

This code is perfectly done thing into JSON

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

First parse xml and convert data to array:

$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];
Pubudu Jayawardana
  • 2,250
  • 1
  • 13
  • 18