PHP curl echo没有显示在浏览器中

问题描述 投票:0回答:2

我正在尝试在浏览器中显示来自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文件,则会出现黑屏。我可以回显其他字符串,例如:

Example echo

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

php curl post wamp wampserver
2个回答
0
投票

由于返回是一个对象,因此必须遵循其对象链来访问它。无法执行echo对象,必须检索message属性并返回字符串。

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

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

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

curl_close($ch);

参考:Object


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.