-1

我的代码:

private static $API_ACCESS_KEY = 'AIzaSyDG3fYAj1uW7VB-wejaMJyJXiO5JagAsYI';
$headers = array(
            'Authorization: key=' .self::$API_ACCESS_KEY,
            'Content-Type: application/json');

private function useCurl(&$model, $url, $headers, $fields = null) {
            // Open connection
                $ch = curl_init();
            if ($url) {
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Disabling SSL Certificate support temporarly
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            if ($fields) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            }

            // Execute post
            $result = curl_exec($ch);
            if ($result === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            // Close connection
            curl_close($ch);

            return $result;
    }
}

错误:

curl_setopt():您必须使用 CURLOPT_HTTPHEADER 参数传递对象或数组

4

1 回答 1

0

$headers 根本不是一个数组。确保它是一个数组,如果不是,则抛出 InvalidArgumentException。像这样:

private function useCurl(&$model, $url, $headers, $fields = null) {
if(!is_array($headers)){throw new InvalidArgumentException('headers MUST be an array!');}
...

或者,从 PHP7 开始,

private function useCurl(&$model, $url, array $headers, $fields = null) {
...

请注意,虽然您在上面声明了一个名为 $headers 的变量,但它在函数定义之外,因此在函数范围之外。函数的 $headers 是输入参数 #3

于 2016-06-15T15:09:54.447 回答