簡體   English   中英

如何將 SOAP API 響應從 XML 轉換為 JSON

[英]How to convert SOAP API response from XML to JSON

<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>

這是 API 的結果,但我想將其轉換為:

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

我該怎么做? 我試過json_encodejson_decode但它對我不起作用。 我應用了不同的方法來轉換它,但它仍然顯示 XML 結果。 誰能告訴我如何將其轉換為 JSON?

這是關於使用 xml https://stackoverflow.com/a/3577662/3266626 的可用選項的一個很好的答案

我使用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>";

編輯:替換

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

$doc = new DOMDocument();
$doc->loadXML($xml);

我在該鏈接上找到了解決方案,感謝大家幫助我以這種方式使用 api 響應如何將 SOAP 響應轉換為 PHP 數組?

$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);

這段代碼完美地完成了 JSON

首先解析xml並將數據轉換為數組:

$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM