<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_encode
和json_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 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
首先解析xml并将数据转换为数组:
$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];