使用 PHP 的 CURL 不显示响应

Posted

技术标签:

【中文标题】使用 PHP 的 CURL 不显示响应【英文标题】:CURL using PHP not displaying response 【发布时间】:2017-07-15 03:16:19 【问题描述】:

我正在尝试在我的 php 文件中运行 CURL 命令,但我看不到输出。以下内容略有修改,没有真实的用户名/密码/URL。 我试图查看输出的原因是确保 CURL 命令按预期工作(我已经在 bash 中运行它,所以我知道预期的结果)。

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: text/plain;charset=utf-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, '$username:$password');
curl_setopt($ch, CURLOPT_POSTFIELDS, '$data');

// grab URL and pass it to the browser
curl_exec($ch);

我已运行以下命令以确保 CURL 与我的 PHP 服务器一起安装,情况就是这样:

function _is_curl_installed() 
    if  (in_array  ('curl', get_loaded_extensions())) 
        return true;
    
    else 
        return false;
    


// Ouput text to user based on test
if (_is_curl_installed()) 
  echo "cURL is <span style=\"color:blue\">installed</span> on this server";
 else 
  echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";

我做错了什么吗?我已经在我的 bash 上运行 curl 命令,并且可以看到响应正常:

curl -X POST --user $username:$password --header "Content-Type: text/plain;charset=utf-8" --header "Accept: application/json" --data-binary @Test.txt "http://www.example.com"

【问题讨论】:

【参考方案1】:

试试这个例子:

<?php
// SEND CURL POST DATA
 $jsonData = array(
    'user' => 'Username',
    'pass' => 'Password'
); 
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//API Url
$url = 'http://fxstar.eu/JSON/api.php';
 //Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1); 
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); 
//Set the content type to application/json
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));  
curl_setopt($ch, CURLOPT_HTTPHEADER, array(Content-Type: text/plain;charset=utf-8); 
//Execute the request
echo $result = curl_exec($ch);
?>

从js中获取json:

<?php
// GET JSON CONTENT FROM JS api.php
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);
?>

【讨论】:

对我没用。有什么小提琴的例子吗? ***.com/questions/31970541/… 教程ryansechrest.com/2012/07/… 工作 curl 发布,发布 json,获取方法:github.com/fxstar/openshift/blob/master/curl/…

以上是关于使用 PHP 的 CURL 不显示响应的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的 php curl 代码不显示任何内容? [复制]

cURL 已启用但不工作且未在 phpinfo() 中显示

cURL - 在详细模式下,它不显示我发布的文件的内容

php如何执行linux的curl指令

PHP/Curl/Wordpress 在不刷新页面的情况下发布数据,curl 不起作用

如何在不使用 ajax 刷新的情况下在我的页面上显示我的 php 响应?