【问题标题】:CURLOPT_POSTFIELDS array of folder contentCURLOPT_POSTFIELDS 文件夹内容数组
【发布时间】:2014-11-14 16:05:42
【问题描述】:

我正在向 Google 文本转语音发送 curl 帖子。我有一组 .flac 文件,我想将其发送到 Google Text to Speech 服务,以便将内容写入 txt 文件。

这是我为此编写的代码,它可以工作:

$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);
    }
}

它就像一个魅力,在“pum.txt”中我写了所有文件内容,没关系。

我的问题是我不想每次都添加到数组“cont2”中,我需要传递的文件的新名称在“flac 文件夹”中。

为避免这种情况,我使用“scandir”方法,删除“。”和 ".." 字符串,并将该数组提供给 CURL_OPT_POSTFIELD,但对 GTT 的调用返回一个空内容。

这是我为此编写的代码(而不是 $cont2 数组)

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

print_r 和 $cont2 数组一样:

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

但 Google TTS 返回空结果。

谁能告诉我哪里出错了?

亲切的问候

布鲁斯

编辑:使用 "$cont = glob("$directory/*.flac");"解决了这个问题。希望对其他人有所帮助。

【问题讨论】:

    标签: php arrays curl google-text-to-speech


    【解决方案1】:

    scandir() 不会包含完整的路径信息——它只会返回文件名。因此,当您构建文件名数组以循环并发送到 google 时,您必须自己包含这些目录。

    例如

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

    例如扫描目录将返回file1.flac,但您需要有flac/file1.flac。由于您没有包含路径信息,因此您尝试对不存在的文件名执行 file_get_contents(),并向 Google 发送布尔值 false(file_get 失败)。

    【讨论】:

    • 还要感谢您,您的解释非常棒。它解决了我在项目的另一部分中遇到的问题。
    【解决方案2】:

    正如 Marc B 所说,您需要丢失文件的目录。我只会使用glob,因为它会返回您需要的内容:

    $cont = glob("$directory/*.flac");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多