简体   繁体   中英

curl to php to post a json and audio

I'm trying to convert a curl command to be used in a php script

   curl -k -F "request={'timezone':'America/New_York','lang':'en'};type=application/json" -F "voiceData=@d8696c304d09eb1.wav;type=audio/wav" -H "Authorization: Bearer x" -H "ocp-apim-subscription-key:x" "http://example.com"

and here is my php script

<?
$data = array("timezone" => "America/New_York", "lang" => "en", "voiceData" => "d8696c304d09eb1.wav");                                                                    
$data_string = json_encode($data);                                                                                   
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-type: application/json',
   'Authorization: Bearer x',
   'ocp-apim-subscription-key:x')
);
$result = curl_exec($ch);
?>

I understand that the send audio file bit is not right but i cant find an example how to post it.

I have edited this in response to the post fields but if I include $ch i get no output if don't include the output complains that no post request. Any ideas?

<?
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-type: application/json',
   'Authorization: Bearer x',
   'ocp-apim-subscription-key:x')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 
    array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
          'voicedata' => new CURLFile("d8696c304d09eb1.wav")
    )
);
$result = curl_exec($ch);
echo $result;
?>

You're missing the request= in your POST fields. Also, sending files using @filename is deprecated, you should use the CURLFile class.

curl_setopt($ch, CURLOPT_POSTFIELDS, 
    array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
          'voicedata' => new CURLFile("d8696c304d09eb1.wav")
    )
);

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