What is the most reliable method for raw text printing to a dot-matrix printer (Epson ESC/P) from a PHP web application?

I am developing a web-based application using PHP 7.4 a Point-of-Sale or inventory system. A requirement for this project is to print receipts/invoices to a legacy Epson LQ-2180 dot-matrix printer, which is connected directly to the server via USB.

The goal is to print in text-mode for speed and to use the printer’s built-in fonts and formatting capabilities (like bold, condensed text, and paper cutting) using ESC/P control codes. I do not want to use a graphical driver, as the output must be raw text.

So far, I have identified two primary approaches:

  1. Direct Device Writing: Using PHP’s file functions to write directly to the printer’s device file.
<?php
   define('ESC', "x1B");
   define('BOLD_ON', ESC . 'E');
   $printer = fopen('/dev/usb/lp0', 'w');
   fwrite($printer, BOLD_ON . "Hello Worldn");
   fclose($printer);
?>

My concern here is managing file permissions correctly and securely for the web server user (www-data).

  1. Using Shell Commands: Using shell_exec() to pass the data to the OS printing system (CUPS), which is configured with a raw queue.
<?php
   $text = "Hello Worldn";
   file_put_contents('/tmp/printjob.txt', $text);
   shell_exec("lp -d Epson_LX310_RAW -o raw /tmp/printjob.txt");
?>

This seems more robust, but I am not sure if it’s the standard way to handle this.

Considering reliability, security, and performance, what is the modern best practice for sending raw ESC/P jobs to a dot-matrix printer from a server-side PHP application? Are there any libraries that simplify this process, or is one of the above methods clearly superior?