简体   繁体   中英

Convert JavaScript Get Request to PHP Curl

My PHP Curl code is not returning an error or any response text. The JavaScript code I based it off of returns a Json Array.

PHP Curl

  header('Access-Control-Allow-Origin: ' . $_SERVER['SERVER_NAME']);

  $subscriptionKey = '';

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://southcentralus.tts.speech.microsoft.com/cognitiveservices/voices/list');
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Ocp-Apim-Subscription-Key", $subscriptionKey));
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);

  if($response === false)
  {
      echo 'Curl error: ' . curl_error($ch);
  }
  else
  {
      echo 'Operation completed without any errors<br>';
      echo "Response: $response";
  }
  $voices = json_decode($response);

  curl_close($ch);

PHP Results

PHP 结果图像Working Javascript

    var request = new XMLHttpRequest();
    var subscriptionKey = '';
    request.open('GET', 'https://southcentralus.tts.speech.microsoft.com/cognitiveservices/voices/list', true);

    request.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            const response = this.response;
            const data = JSON.parse(response);
            console.log(data);
        } else {
            window.console.log(this);
        }
    };

    request.send()

JavaScript Results

JavaScript 输出图像

I changed CURLOPT_HEADER to true (thanks to Lucas's comments) and now get a 401 error. This puzzles me because it is the exact same URL and Subscription key.

The array for CURLOPT_HTTPHEADER takes one item per header, rather than separate items for key & value. So in this case, try:

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Ocp-Apim-Subscription-Key: $subscriptionKey"));

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