使用PHP的CURL不显示响应

时间:2017-02-24 10:20:10

标签: php html bash curl xampp

我试图在我的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);

我已经运行以下内容以确保我的PHP服务器安装了CURL,情况就是这样:

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 个答案:

答案 0 :(得分:1)

试试这个例子:

httpcore-4.3.2

从js获取json:

<?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);
?>