【问题标题】:PHP curl echo not displaying in browserPHP curl回显未在浏览器中显示
【发布时间】:2019-12-05 11:22:14
【问题描述】:

我正在尝试在浏览器中显示来自 PHP POST 请求的响应字符串。如果我跑:

<?php
$project_id = "abcdefgh";
$session_id = "123456789";
$url = "https://dialogflow.googleapis.com/v2/projects/".$project_id."/agent/sessions/".$session_id.":detectIntent";

$query = '{
            "query_input": {
            "text": {
                "text": "Test input",
                "language_code": "en-US"
            }
            }
        }';

//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, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $query);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//execute post
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>

在 VSCode 中,我得到以下响应(这是预期行为):

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

但是,如果我在 Chrome 中导航到我的 WAMP 服务器上运行的 index.php 文件,我会看到一个空白屏幕。我可以回显其他字符串,例如:

我什至可以直接复制响应,并将响应作为字符串在浏览器中回显。它似乎不适用于发布请求(也许这是一个时间问题?)。这可能是 WAMP 配置/权限问题,但我觉得问题可能出在其他地方。感谢您的帮助!

【问题讨论】:

  • 日志是怎么说的?
  • 您要恢复错误消息吗?
  • 在本地执行您的代码,可以得到您所说的预期结果。 “我得到一个空白屏幕。” - 您是否启用了适当的 PHP 错误报告?如果没有,请先这样做。
  • 您必须进行身份验证并告诉 curl 以 JSON 格式发送 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Bearer add_token_here_'));
  • 使用 var_dump($result) 或使用 print_r($result);

标签: php curl post wamp wampserver


【解决方案1】:

因为你的 return 是一个对象,你必须通过它的对象链来访问它。无法执行echo一个对象,必须取回message属性并返回一个字符串。

//execute post
$result = curl_exec($ch);

// Decode object ()
$result = json_decode($result);

// Message error
echo $result->error->message;

curl_close($ch);

参考:Object

【讨论】:

  • 一个 var_dump 给了我字符串 (304)。运行您的代码时出现以下错误:imgur.com/1EBSMOj
  • 由于 curl 响应没有关键的“错误”或“消息”,因此您得到了它。我想 curl 调用应该有一些错误。
【解决方案2】:

我必须下载 cacert.pem 并将其添加到我的 php.ini 文件中,然后重新启动我的 WAMP 服务器以使其工作。 curl 调用出错。

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 2018-12-02
    • 2021-03-05
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多