Reputation: 31
<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?
Upvotes: 0
Views: 9844
Reputation: 31
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
Upvotes: 2
Reputation: 151
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);
Upvotes: 2
Reputation: 2365
First parse xml and convert data to array:
$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];
Upvotes: 0