PHP之XML格式与Array类型的互相转换!

微信开发中 两者互相转换的场景太多了!

我用的言哥的Composer包组件

下面两个转换方法亲测有效!

其中我array转xml用的言哥组件

XML转array用的下方方法!

XML转Array!

//xml转换成数组
   private function xmlToArray($xml) {
      //禁止引用外部xml实体
      libxml_disable_entity_loader(true);
      $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
      $val = json_decode(json_encode($xmlstring), true);
      return $val;
   }   

言哥组件使用代码如下

$spbill_create_ip = $this->getip(); //用户ip
        //生成sign的数组
        $data = array(
            'appid' => 'wx6c96456a69725',//appid
            'attach' => 'test',
            'body' => 'paytest',
            'mch_id' => '12302',//mchid
            'nonce_str' => 'asdasdasdas',
            'notify_url' => 'http://admin.php1314.cn/index/xx/xx',
             'out_trade_no' => '123456789012',
             'spbill_create_ip' => $spbill_create_ip,
             'total_fee' => '1',
             'trade_type' => 'JSAPI',
             'openid' => 'oGQrns3IyCED4uy23ldGgs',
        );

        $sign = $this->unifiedsign($data,$this->apiKey);//获取sign
        $unifiedorder = [
            'xml' => $data,
        ];
        $unifiedorder['xml']['sign'] = $sign;//将sign赋值进xml模板中
        $openid = session('openid');
        // var_dump($openid);
        $data = Xml::getInstance()->arrayToXml($unifiedorder, false); //Array转xml

Array转XML

//数组转换成xml
      private function arrayToXml($arr) {
        $xml = "<root>";
        foreach ($arr as $key => $val) {
          if (is_array($val)) {
            $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
          } else {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
          }
        }
        $xml .= "</root>";
        return $xml;
      }

为您推荐

评论已关闭