通过cURL发布HTML内容

时间:2013-04-22 12:51:05

标签: php curl

我有以下代码:

$poststr = "param1=<html><head></head><body>test1 & test2</body></html>&param2=abcd&param3=eeee";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.mytest.com");
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $poststr);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);

该帖子无效,我猜它与param1中包含HTMl的事实有关。但是,如果我使用htmlentities(),它就无济于事。我尝试过使用urlencode(),但仍然没有。

1 个答案:

答案 0 :(得分:0)

不要忘记&是一个特殊的网址分隔符 在您的示例中,<body>test1 & test2</body>被解释为错误 $poststr必须仔细进行urlencoded。这是正确的方法:

$poststr = "param1=".rawurlencode('<html><head></head><body>test1 & test2</body></html>')."&param2=abcd&param3=eeee";

你应该编码它的所有部分:param2和param3 最简单的方法是使用数组和html_build_query():

$params = array();
$params['param1'] = '<html><head></head><body>test1 & test2</body></html>';
$params['param2'] = 'abcd';
$params['param3'] = 'eeee';

//or
//$params = array( 'param1' => '<html><head></head><body>test1 & test2</body></html>',
//                 'param2' => 'abcd',
//                 'param3' => 'eeee'
//               );

$poststr = html_build_query($params);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.mytest.com");
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $poststr);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);