CURLOPT_POSTFIELDS array of folder content

236 views Asked by At

i'm making a curl post to Google text to speech. I have a set of .flac files, that i want to send to Google Text to Speech service, in order to have the content wrote in a txt file.

This is the code i wrote to do this and it works:

$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';

$cont2 = array(

   'flac/1.flac',
   'flac/2.flac',
   'flac/3.flac'
    );
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

foreach ($cont2 as $fn) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn)); 
    $result = curl_exec($ch);
    $info = curl_getinfo($ch); 
    //var_dump($info);
    if ($result === false) {
       die(curl_error());
    }else{
       echo "<br />".$fn." upload ok"."<br />";
       file_put_contents("pum.txt", $result, FILE_APPEND);
    }
}

It works like a charm, in the "pum.txt" i have all the file content wrote and it's ok.

My problem is that i don't want to add to the the array "cont2", each time, the new name o the files i need to pass to, that there are in the "flac folder".

To avoid that, i use "scandir" method, remove "." and ".." string from the array and give that array to the CURL_OPT_POSTFIELD, but the call to GTT return a empty content.

This is the code i wrote to do that (instead $cont2 array)

$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));

Print_r of that is the same as $cont2 array:

array(3) {
  [3]=>
  string(6) "1.flac"
  [4]=>
  string(6) "2.flac"
  [5]=>
  string(6) "3.flac"
}

But Google TTS return empty result.

Does anyone please tell me where i'm making mistake?

Kind Regards

Brus

EDIT: use "$cont = glob("$directory/*.flac");" solved the issue. Hope help some others.

2

There are 2 answers

0
AbraCadaver On BEST ANSWER

As Marc B states you need the directory to the files which is missing. I would just use glob as it will return exactly what you need:

$cont = glob("$directory/*.flac");
1
Marc B On

scandir() won't include full path information - it'll only return filenames. SO when you're building your array of filenames to loop on and send to google, you'll have to include that directories yourself.

e.g.

$dir = 'flac';
$files = scandir($dir);

foreach($files as $key => $file);
    $files[$key] = $dir . '/' . $file;
}

e.g. scan dir will return file1.flac, but you need to have flac/file1.flac. Since you're not including the path information, you're trying to do file_get_contents() on a filename which doesn't exist, and are sending a boolean false (file_get failed) over to google.