PHP cURL发布失败或没有数据返回我哪里出错了


PHP cURL Post Failing or no Data returning where did I go wrong?

这是我的比特o'php,试图弄清楚为什么我没有得到一个$result。它生成的URL将根据get或post给我一个有效的JSON结果。所以我认为我的问题是如何使用cURL。所以我需要有人来处理这个。

        //open connection
        $ch = curl_init();
        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,count($params));
        curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
        //execute post
        $result = curl_exec($ch);           
                    if(!$result)
                    {
                        $error = curl_error($ch); echo $error; return false;
                    }
        //close connection
        curl_close($ch);
        //return json_decode($result);
                    echo $result;

编辑代码来自原始文章

$error不报告任何内容。我更改了返回json。。。以进行回声,查看它是否在做任何事情,并打印出"不允许的关键字符"'显示在屏幕上。

编辑2

$url = http://domain.com/search
$params = array('q'=>'search,term')

$params通过foreach循环,该循环构建$fields_string

$fields_string = '?';
foreach($params as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = substr($fields_string,0,-1);

fields_string最终看起来像?ll=37.2790669,-121.874722&range=10(对于我目前正在做的事情,我有1-12个可选参数可以传递,这就是为什么我以现在的方式构建它。

尝试添加错误检查以确保curl_exec成功执行,并在服务器上返回有意义的错误消息。

类似于:

    $ch = curl_init();
    //Make string url safe with urlencode
    curl_setopt($ch,CURLOPT_URL,urlencode($url));
    curl_setopt($ch,CURLOPT_POST,count($params));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    if(!$result) {
        $error = curl_error();
        //$error now contains the error thrown when curl_exec failed to execute
        //echo this to terminal or to an error box in the browser?
    }
    curl_close($ch);
    return json_decode($result);

如果您仍然需要帮助,请在此处发布您的错误。此外,以下是我利用的两个功能的手册页面:

http://www.php.net/manual/en/function.curl-error.php

http://www.php.net/manual/en/function.curl-exec.php

http://php.net/manual/en/function.urlencode.php

-干杯

//set POST variables
$url = "http://example.com/edsym/registration.php"; // URL to calc.cgi
$fields = array(
'namee'=>urlencode($name),
'city'=>urlencode($city),
'phh'=>urlencode($ph),
'emaill'=>urlencode($email),
'msg1'=>urlencode("Message type")
                );
$fields_string=" ";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);

我正在使用curl来发布这样的帖子及其工作