php微信 - 6自動回覆

自動回覆

public function getpost()
    {
        //獲取用戶傳送過來的xml
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        file_put_contents('demo.txt',$postStr);
        if(!empty($postStr)){

            //解析post來的XML爲一個對象$postObj
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName; //請求消息的用戶
            $toUsername = $postObj->ToUserName; //"我"的公衆號id
            $keyword = trim($postObj->Content); //消息內容
            $time = time(); //時間戳
            $msgtype = 'text'; //消息類型:文本
            $textTpl = "
                <xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                </xml>";

            if($keyword){
                $contentStr = $keyword;

                //sprintf裏的參數要以textTpl裏的節點一一對應代替有%s的地方。但是要注意$fromUsername, $toUsername。他們的值是要互換的!

                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
                echo $resultStr;
                exit();
            }

        }else {
            echo "";
            exit;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章