如何将API响应从XML转换为JSON

时间:2017-09-28 17:22:46

标签: php json xml api

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

3 个答案:

答案 0 :(得分:2)

对于使用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);

答案 1 :(得分:1)

我在该链接上找到了解决方案,感谢各位帮忙     以这种方式使用api响应有助于我     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);

这段代码完美地融入了JSON

答案 2 :(得分:0)

首先解析xml并将数据转换为数组:

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