HTTP周りのプログラムをする時に便利なZend_Http_Clientなんですが、同名のパラメーターを複数渡す時に軽くつまずいてしまいました。
以下のように、同名のパラメータを複数POSTしたい場合のお話です。
tag=php&tag=zend
Zend_Http_Clientには
- Zend_Http_Client::setParameterPost
というメソッドがあるので、まずはそれを使ってみました。
<?php
set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path());
require_once 'Zend/Http/Client.php';
$client = new Zend_Http_Client('http://example.org');
$client->setParameterPost(array('tag' => array('php', 'zend'))); // 配列で渡す方法
$client->setParameterPost('category', array('it', 'programming')); // key, valueで渡す方法
$client->request('POST');
var_dump($client->getLastRequest());
上の実行結果が以下。
[massat@localhost ~]$ php ./request.php string(265) "POST / HTTP/1.1 Host: example.org Connection: close Accept-encoding: gzip, deflate User-Agent: Zend_Http_Client Content-Type: application/x-www-form-urlencoded Content-Length: 77 tag%5B0%5D=php&tag%5B1%5D=zend&category%5B0%5D=it&category%5B1%5D=programming"
URLエンコードされていますが、要は
tag[0]=php&tag[1]=zend&category[0]=it&category[1]=programming
というパラメータが作られている訳です。
PHPが同名のリクエストパラメータを処理できない仕様のため、Zend_Http_Clientが気を利かしてやっているのでしょうか。
しかし今回はこれだとだめなので、代わりに
- Zend_Http_Client::setRawData
というメソッドを使いました。
<?php
set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path());
require_once 'Zend/Http/Client.php';
$client = new Zend_Http_Client('http://example.org');
$parameter = sprintf('tag=%s&tag=%s&category=%s&category=%s', urlencode('php'), urlencode('zend'), urlencode('it'), urlencode('programming'));
$client->setRawData($parameter); // 生データをセット
$client->request('POST');
var_dump($client->getLastRequest());
結果が以下。
[massat@localhost ~]$ php ./request.php string(237) "POST / HTTP/1.1 Host: example.org Connection: close Accept-encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded User-Agent: Zend_Http_Client Content-Length: 49 tag=php&tag=zend&category=it&category=programming"
これで、望む形式のリクエストパラメータを生成できました。
以上ちょっとしたことですが、メモまで。