PHP如何将XML字符串转数组?
PHP如何将XML字符串转数组?
首先使用函数“simplexml_load_string()”,将XML字符串转为对象;
$obj = simplexml_load_string($str,"SimpleXMLElement", LIBXML_NOCDATA);
然后使用“json_encode()”函数将对象转为JSON字符串;
$json_str = json_encode($obj);
最后使用“json_decode()”转为数组即。
$xml_arr = json_decode($json_str, true);
完整代码
$str = '<xml> <ToUserName> <![CDATA[gh_fc0a06a20993]]> </ToUserName> <FromUserName> <![CDATA[oZI8Fj040-be6rlDohc6gkoPOQTQ]]> </FromUserName> <CreateTime>1472549042</CreateTime> <MsgType> <![CDATA[event]]> </MsgType> <Event> <![CDATA[user_consume_card]]> </Event> <CardId> <![CDATA[pZI8Fj8y-E8hpvho2d1ZvpGwQBvA]]> </CardId> <UserCardCode> <![CDATA[452998530302]]> </UserCardCode> <ConsumeSource> <![CDATA[FROM_API]]> </ConsumeSource> <LocationName> <![CDATA[]]> </LocationName> <StaffOpenId> <![CDATA[oZ********nJ3bPJu_Rtjkw4c]]> </StaffOpenId> <VerifyCode> <![CDATA[]]> </VerifyCode> <RemarkAmount> <![CDATA[]]> </RemarkAmount> <OuterStr> <![CDATA[xxxxx]]> </OuterStr> </xml>'; $obj = simplexml_load_string($str,"SimpleXMLElement", LIBXML_NOCDATA); $test = json_decode(json_encode($obj),true); $arr = [ 'FromUserName' => $test['FromUserName'], 'ToUserName' => $test['ToUserName'], 'CreateTime' => $test['CreateTime'], 'CardId' => $test['CardId'], 'UserCardCode' => $test['UserCardCode'], 'ConsumeSource' => $test['ConsumeSource'], 'StaffOpenId' => $test['StaffOpenId'] ]; $arr = array_map('trim',$arr); var_dump($arr);
推荐教程:《PHP》