将XML字符串解析为JSON数组

时间:2017-11-14 05:24:43

标签: php arrays json

$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';

无法捕获'status num =“923337896466”'并未能抓住日期=“14-11-2017 10:02:58”

JSON输出应该是:

{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "status num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "status num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';

$xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

输出

{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}