dopnpoh056622
2015-12-08 14:57
浏览 92
已采纳

cURL脚本无法正常工作

I have a script, that when a variable is given to it using the GET method, it echoes the variable. I want to take this variable and use it on another script. This is what I have done

<?php $ch = curl_init("http://website.com/test.php?str=test");
$response = curl_exec($ch);
curl_close($ch);

echo $response; ?>

But the $response variable cointains this:

1

I don't know what I have done wrong but if someone can help me, I would really appretiate it.

图片转代码服务由CSDN问答提供 功能建议

我有一个脚本,当使用GET方法给它一个变量时,它会回显变量。 我想取这个变量并在另一个脚本上使用它。 这就是我所做的

 &lt;?php $ ch = curl_init(“http://website.com/test.php?str=test”); 
  $ response = curl_exec($ ch); 
curl_close($ ch); 
 
echo $ response;  ?&gt; 
   
 
 

但是$ response变量包含了这个:

1 \ n

我不知道自己做错了什么,但如果有人可以帮助我,我会非常乐意。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanhun3273 2015-12-08 15:02
    已采纳

    You need to set CURLOPT_RETURNTRANSFER in order to get the response body from curl_exec.

    Try this, from http://php.net/manual/en/function.curl-setopt.php:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    

    before you call curl_exec.

    已采纳该答案
    打赏 评论
  • donglu5047 2015-12-08 15:07

    This is How You need to use CURL Power of PHP :)

    <?php 
            // create curl resource 
            $ch = curl_init(); 
    
            // set url 
            curl_setopt($ch, CURLOPT_URL, "http://website.com/test.php?str=test"); 
    
            //return the transfer as a string 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    
            // $output contains the output string 
            $output = curl_exec($ch); 
    
            // close curl resource to free up system resources 
            curl_close($ch);
    
            echo $output;
    

    ?>

    You can follow php manual

    打赏 评论
  • doudan1123 2015-12-08 15:09

    This is a basic example of a curl REST call. CURLOPT_RETURNTRANSFER is indeed needed for a response.

     <?php
    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => "http://website.com/test.php?str=test",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "postman-token: a852dce0-568e-41c8-0bc0-9e99fef9d09f"
      ),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }
    
    打赏 评论

相关推荐 更多相似问题