将多个结果作为带有换行符的单条消息发送到 PHP 中的电报机器人

Send multiple results as single message with line breaks to telegram bot in PHP

我正在 运行 对图像文件夹中的图像进行 tesseract,如果 OCR 结果有“发生错误”文本,那么我想发送所有带有错误消息的图片名称,并将其连接为带有换行符的单个消息当然是每条消息。

使用下面的代码,我会收到每张图片结果的单独消息。

但我想要像这张图片中那样的东西作为一条消息。

这是我的代码;

$dir = "images/*.jpg";

$images = glob( $dir );

foreach( $images as $image):

$result = (new TesseractOCR($image))
->run();

$info = pathinfo($image);
$file_name =  basename($image,'.'.$info['extension']);
$Name = str_replace("_"," ", $file_name);

$msg = "Error Occurred";

if($result === $msg)
{
    $err = $Name . " - Says - ".$msg."\n";

    $apiToken = $bot_token;
    $data = [
        'chat_id' => $chat_id,
        'text' => $err
    ];
    $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );
    
}
else 
{
    

    $msg = $Name . " - Good! \n";

    echo $msg."</br>";

}

endforeach;

消息的发送需要发生在 foreach 循环之外

我更改了代码以将所有错误收集到一个数组中,然后在循环之后如果存在任何错误,它将数组内爆为多行字符串并发送消息

<?php

$dir = "images/*.jpg";

$images = glob($dir);

$errors = [];

foreach ($images as $image) {

    $result = (new TesseractOCR($image))
        ->run();

    $info = pathinfo($image);
    $file_name = basename($image, '.' . $info['extension']);
    $Name = str_replace("_", " ", $file_name);

    $msg = "Error Occurred";

    if ($result === $msg) {
        $errors[] = $Name . " - Says - " . $msg;
    }
    else {
        $msg = $Name . " - Good! \n";
        echo $msg . "</br>";
    }
}

if (count($errors) > 0) {
    $apiToken = $bot_token;
    $data = [
        'chat_id' => $chat_id,
        'text' => implode("\n", $errors)
    ];
    $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data));
}