如何使用PHP代码将XML结果转换为JSON数组或PHP数组

时间:2019-04-05 01:55:54

标签: php html arrays json xml

我想使用PHP 5.6将以下代码从XML转换为PHP数组,或者从XML转换为JSON数组。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <readDataResponse xmlns="http://tempuri.org/">
      <readDataResult>
        <sampleItems>
          <SampleModel>
            <sampleId>1</sampleId>
            <firstName>Amran</firstName>
            <lastName>Aditya</lastName>
          </SampleModel>
          <SampleModel>
            <sampleId>2</sampleId>
            <firstName>Abeds</firstName>
            <lastName>Lukman</lastName>
          </SampleModel>
        </sampleItems>
      </readDataResult>
    </readDataResponse>
  </soap:Body>
</soap:Envelope>

2 个答案:

答案 0 :(得分:1)

XML到JSON:

{
    "Envelope": {
        "Body": {
            "readDataResponse": {
                "readDataResult": {
                    "sampleItems": {
                        "SampleModel": [
                            {
                                "sampleId": "1",
                                "firstName": "Amran",
                                "lastName": "Aditya"
                            },
                            {
                                "sampleId": "2",
                                "firstName": "Abeds",
                                "lastName": "Lukman"
                            }
                        ]
                    }
                },
                "_xmlns": "http://tempuri.org/"
            },
            "__prefix": "soap"
        },
        "_xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
        "_xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "_xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
        "__prefix": "soap"
    }
}

XML到PHP:

How to convert XML into array in PHP?

答案 1 :(得分:0)

在这里您可以将xml字符串转换为json JSON转换为数组

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);