日度归档:2021年1月30日

php将字符串转为二进制数据串

/**
    * 将字符串转换成二进制
    * @param type $str
    * @return type
    */
    function StrToBin($str){
        //1.列出每个字符
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        //2.unpack字符
        foreach($arr as &$v){
            $temp = unpack('H*', $v);
            $v = base_convert($temp[1], 16, 2);
            unset($temp);
        }

        return join(' ',$arr);
    }

    /**
    * 将二进制转换成字符串
    * @param type $str
    * @return type
    */
    function BinToStr($str){
        $arr = explode(' ', $str);
        foreach($arr as &$v){
            $v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
        }
        return join('', $arr);
    }

原文:https://www.cnblogs.com/chenggege/p/7761287.html

php接口返回xml格式

在头部加上

  header("Content-type: application/xml");

范例:

$res = $this->arrayToXml($data,$amount['count'],$page_count,$page);
header("Content-type: text/xml");
echo $res;
//数组转XML
    public function arrayToXml($data,$amount,$page_count,$page)
    {
//    	var_dump($data);die;
        $xml = "<response><code>0</code><msg>成功</msg><total_results>{$amount}</total_results><total_page>{$page_count}</total_page><current_page>{$page}</current_page><order_list>";
 
        foreach ($data as $key=>$val)
        {
            $xml.= "<order><modified></modified><receiver_zip>-</receiver_zip><is_tax>false</is_tax><invoice_type></invoice_type><invoice_title></invoice_title><buyer_cod_fee>0.0</buyer_cod_fee><point_fee></point_fee><coupon_pay></coupon_pay><payments></payments>";
            foreach($val['order'] as $k=>$v){
                if (is_numeric($v)){
                    $xml.="<".$k.">".$v."</".$k.">";
                }else{
                    $xml.="<".$k.">".$v."</".$k.">";
                }
            }
            $xml.= "<itemlist>";
            foreach($val['itemlist'] as $key=>$vv){
                $xml.= "<item>";
                foreach($vv as $kk=>$vs){
                    $xml.="<".$kk.">".$vs."</".$kk.">";
                }
                $xml.= "<shop_sku_id></shop_sku_id><sku_name></sku_name><oid></oid><amount></amount></item>";
            }
            $xml.= "</itemlist>";
            $xml.= "</order>";
 
        }
        $xml.="</order_list></response>";
        return trim($xml);
    }