首页 > 解决方案 > 我需要将文件另存为 name_01,name_02

问题描述

您好我需要将图像名称保存为 name_01,name_02 但我尝试了 5 个多小时我无法摆脱这个请检查代码并帮助我

if ($typeMessage == 'image') {
    $responseMedia = $bot - > getMessageContent($idMessage);
    if ($responseMedia - > isSucceeded()) {
        //  getRawBody() binary 

        $dataBinary = $responseMedia - > getRawBody(); // return binary
        // get file type from header
        $fileType = $responseMedia - > getHeader('Content-Type');

        if (preg_match('/image/', $fileType)) {

            list($fileType, $ext) = explode("/", $fileType);
            $ext = ($ext == 'jpeg' || $ext == 'jpg') ? "jpg" : $ext;
            if (!file_exists($fileFullSavePath)) {
                $counter = 1;

                $fileNameSave = 'lamsam_'.$counter.
                ".".$ext;
                else if (file_exists($fileFullSavePath)) {
                    $counter++;
                    $fileNameSave = 'lamsam_'.$counter.
                    ".".$ext;
                }
            }
        }


        $botDataFolder = 'LAMSAM PAPER/'; // main save file folder
        $botDataUserFolder = $botDataFolder.$sourceType.$sourceId; // sub folder= sourceId 
        if (!file_exists($botDataUserFolder)) { // check if don't have folder sourceId
            mkdir($botDataUserFolder, 0777, true);
        }
        // path 
        $fileFullSavePath = $botDataUserFolder.
        '/'.$fileNameSave;
        file_put_contents($fileFullSavePath, $dataBinary);

我期待输出

但实际只是

标签: php

解决方案


首先,我们看不到任何循环,因此$counter不太可能影响任何事情,除非您如下所示循环遍历它。

您可以打开一个文件 ( fopen()),然后fwrite()向其中写入 ( ) 数据。将数据写入其中后,您需要关闭 ( fclose()) 文件:

$fp = fopen('file.txt', 'a+'); //Append mode
// $fp = fopen('file.txt', 'w'); //Write mode
fwrite($fp, $data);
fclose($fp);    

fopen()https ://www.php.net/manual/en/function.fopen.php

fwrite()https ://php.net/manual/en/function.fwrite.php

fclose()https ://www.php.net/manual/en/function.fclose.php

在一个循环中:

这将遍历所有图像,并创建您需要的命名约定:

从 1开始,$i所以应该$i小于或等于$noOfFiles继续有了它,我看不到你将如何增加。loop$_SESSIONcounter$counter

for($i = 1; $i <= $noOfFiles; $i++) {
    $fp = fopen('lamsam_' . $i .'.jpg', 'w');
    fwrite($fp, $data[$i]);
    fclose($fp);    
}

lamsam_1.jpglamsam_2.jpg

您将需要计算$noOfFilesfor 循环,并在$data数组中包含图像的数据。

编辑回复更新

您需要将所有图像文件数据(即每个图像)存储在$dataBinary. 所以$dataBinary需要是一个数组:

$dataBinary = array(
    $image1BinaryData,
    $image2BinaryData,
    $image3BinaryData,
    $image4BinaryData,
    $image5BinaryData,
    $image6BinaryData,
    $image7BinaryData,
    $image8BinaryData,
    $image9BinaryData
    $image10BinaryData    
);

所以..如果您使用 获取图像$responseMedia->getRawBody(),那么您要么希望它作为一个数组出现(如果你得到相同的图像,它似乎只得到一个图像)......或者你也想要循环通过任何可用的方法来获取您所追求的所有图像并将它们添加到数组中。

然后在您的循环中,使用数组$i的索引$dataBinary,您还可以循环浏览要添加到每个文件的图像,而不仅仅是创建 10 个名称不同但图像相同的文件:

for($i = 0; $i <= $num_files;) {
  $i++;
  $fp = fopen('lamsam_' . $i .'.jpg', 'w');
  fwrite($fp, $dataBinary[$i]);
  fclose($fp);
  $fp = $fileNameSave;
}

推荐阅读