使用带数组的file_get_contents发布请求

时间:2015-12-07 18:33:59

标签: php file-get-contents

我尝试通过 file_get_contents 发布请求,但我收到错误500 ,我这样做:

   $params = array("pid" => "000209", "main_widget_pid" => "000209");

    $array = array("method" => "bottomline","params" => $params);

    $url = 'http://example.com/test';
    $data = array('app_key' => '8948a6aa12a1a23Yzglj17QO91Geg', 'methods' => $array);

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );

$context  = stream_context_create($options); 
$result = file_get_contents($url, false, $context);
var_dump($result);

我认为问题在于数组的结构。但我看不出问题。

任何人都可以给我一个方法吗?

1 个答案:

答案 0 :(得分:0)

试试这个补丁:

$data = array('app_key' => '8948a6aa12a1a23Yzglj17QO91Geg', 'methods' => $array);
$http_data = http_build_query($data);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n"
              . "Content-Length: " . strlen($data) . "\r\n",
        'method'  => 'POST',
        'content' => $http_data,
    ),
);

我猜是内容长度标题很重要。

$ options也是如此:

array (
  'http' => 
  array (
    'header' => 'Content-type: application/x-www-form-urlencoded
',
    'method' => 'POST',
    'content' => 'app_key=8948a6aa12a1a23Yzglj17QO91Geg&methods[method]=bottomline&methods[params][pid]=000209&methods[params][main_widget_pid]=000209',
  ),
)

确保它应该是这样的。

php中的错误500意味着在传递了这个$选项之后,你的脚本中出现致命异常。也许你应该调试那里的错误...