如何使用字符串获取curl选项

时间:2013-09-24 04:01:00

标签: php curl

我正在使用PHP 5.3和Curl。

我想让我的curl调用更灵活,因此一个函数可以处理我的所有调用。我遇到的问题是卷曲选项。

它使用CURLOPT_POST等值来表示LONG值。

为了使我的功能更灵活,我想用默认设置这些选项,并根据传递的数组更改它们。

离;

function doCurl($options){
   $defaults = array('CURLOPT_POST' => true, 'CURLOPT_HEADER' => false);
   foreach($options AS $k=>$v) $defaults[$k] = $v;
   foreach($defaults AS $opt_k=>$v) curl_setopt($curl, $opt_k, $v)

}

那么,如何处理$ opt_k以便它可以获得原始变量的LONG值?

3 个答案:

答案 0 :(得分:3)

在我看来,你需要的是一个将字符串转换为PHP常量的函数。您可以使用constant function。您的代码最终会如下所示:

function doCurl($options){
   $defaults = array('CURLOPT_POST' => true, 'CURLOPT_HEADER' => false);
   foreach($options AS $k=>$v) $defaults[$k] = $v;
   foreach($defaults AS $opt_k=>$v) curl_setopt($curl, constant($opt_k), $v)
}

答案 1 :(得分:0)

function doCurl($options) {
   $defaults = array(CURLOPT_POST => true, CURLOPT_HEADER => false);
   curl_setopt_array($curl, !empty($options) ? ($options + $defaults) : $defaults);
}

除了$ curl变量在函数范围内未定义但你可能知道如何处理它的事实。

如果要将字符串转换为常量值,请使用以下内容:

function get_curlopt_from_string($str) {
    if (preg_match('/^CURLOPT_/', $key) && defined($str)) {
        return eval('return $str;');
    }
    return $str;
}

答案 2 :(得分:0)

试试这个例子,它可以帮助您解决问题

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>