简体   繁体   中英

PHP curl echo not displaying in browser

I am trying to display the response string from a PHP POST request in the browser. If I run:

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

in VSCode, I get the following response (this is expected behavior):

{
  "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"
  }
}

However, if I navigate to the index.php file running on my WAMP server in Chrome, I get a blank screen. I can echo other strings, such as:

示例回声

I can even copy the response directly, and echo the response as a string in the browser. It just seems to not work with the post request (maybe it is a timing thing?). This could be a WAMP configuration/permissions problem, but I feel the problem might be elsewhere. Thanks for your help!

Because your return is an object, you must access it by following its object chain. Unable to execute echo an object, you must retrieve the message attribute and return a string.

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

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

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

curl_close($ch);

Reference: Object

I had to download and add cacert.pem to my php.ini file and restart my WAMP server to get it to work. It was an error with the curl call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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