1 $str = '<xml> 2 <ToUserName> <![CDATA[gh_fc0a06a20993]]> </ToUserName> 3 <FromUserName> <![CDATA[oZI8Fj040-be6rlDohc6gkoPOQTQ]]> </FromUserName> 4 <CreateTime>1472549042</CreateTime> 5 <MsgType> <![CDATA[event]]> </MsgType> 6 <Event> <![CDATA[user_consume_card]]> </Event> 7 <CardId> <![CDATA[pZI8Fj8y-E8hpvho2d1ZvpGwQBvA]]> </CardId> 8 <UserCardCode> <![CDATA[452998530302]]> </UserCardCode> 9 <ConsumeSource> <![CDATA[FROM_API]]> </ConsumeSource> 10 <LocationName> <![CDATA[]]> </LocationName> 11 <StaffOpenId> <![CDATA[oZ********nJ3bPJu_Rtjkw4c]]> </StaffOpenId> 12 <VerifyCode> <![CDATA[]]> </VerifyCode> 13 <RemarkAmount> <![CDATA[]]> </RemarkAmount> 14 <OuterStr> <![CDATA[xxxxx]]> </OuterStr> 15 </xml>'; 16 17 $obj = simplexml_load_string($str,"SimpleXMLElement", LIBXML_NOCDATA); 18 $test = json_decode(json_encode($obj),true); 19 $arr = [ 20 'FromUserName' => $test['FromUserName'], 21 'ToUserName' => $test['ToUserName'], 22 'CreateTime' => $test['CreateTime'], 23 'CardId' => $test['CardId'], 24 'UserCardCode' => $test['UserCardCode'], 25 'ConsumeSource' => $test['ConsumeSource'], 26 'StaffOpenId' => $test['StaffOpenId'] 27 ]; 28 $arr = array_map('trim',$arr); 29 var_dump($arr);
在做微信公众号时由于将xml转成对象,每个单独调用时可能会有意外麻烦,所以需要先转成数组,array_map是为了去除空格,因为我发现有部分元素两端是有空格的,造成过功能失效