How to emulate POSTing multiple checkbox form fields myField[] with Zend_Http_Client?

风格不统一 提交于 2019-12-06 06:13:29

The simplest approach may be just to set the raw post body yourself:

$values = array(
    0,
    1,
    2,
);

$key = 'myField';
$rawData = '';
foreach ($values as $value) {
    if ($rawData !== '') {
        $rawData .= '&';
    }
    $rawData .= $key . '%5B%5D=' . $value;
}

$client = new Zend_Http_Client();
$client->setRawData($rawData);
$client->setUri('http://www.davidcaunt.co.uk/');
$client->request(Zend_Http_Client::POST);

$request = $client->getLastRequest();

//Zend_Debug::dump($request);
Zend_Debug::dump(urldecode($request));

Postdata

myField[]=0&myField[]=1&myField[]=2

If you have other variables to send in the postdata, you'll probably want to subclass Zend_Http_Client and override the implementation of _prepareBody() as follows.

This modification aims to remain compatible with future updates, and as such, calls the parent method unless POST params are set, and the form is not multipart (a file upload):

class My_Http_Client extends Zend_Http_Client
{

    function _prepareBody() 
    {
        if (count($this->paramsPost) > 0 && $this->enctype == self::ENC_URLENCODED) {
            $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);

            $body = '';
            foreach ($this->paramsPost as $key => $value) {

                if (is_array($value)) {
                    foreach ($value as $v) {
                        $body .= $key . '%5B%5D=' . $v . '&';
                    }
                } else {
                    $body .= $key . '=' . $value . '&';
                }               
            }

            return rtrim($body, '&');
        }

        return parent::_prepareBody();
    }
}

Usage

$client = new My_Http_Client();
$client->setParameterPost('name', 'John');
$client->setParameterPost('myField', array(0,1,2));
$client->setUri('http://www.davidcaunt.co.uk/');
$client->request(Zend_Http_Client::POST);

$request = $client->getLastRequest();

Zend_Debug::dump(urldecode($request));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!