繁体   English   中英

PHP curl echo未显示在浏览器中

[英]PHP curl echo not displaying in browser

我正在尝试在浏览器中显示来自 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 配置/权限问题,但我觉得问题可能出在其他地方。 谢谢你的帮助!

因为您的返回是一个对象,所以您必须按照它的对象链来访问它。 无法执行echo对象,您必须检索消息属性并返回一个字符串。

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

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

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

curl_close($ch);

参考:对象

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM