Send ZPL to Label Printer in PHP

I needed to generate ZPL data on the fly, and push it to Zebra label printers. I also wanted to be able to see the label on screen, so I also setup an API call to Labelary.

I ended up using pfsockopen(). This example requires Apache’s mod_rewrite and PHP curl.

<?php
$zaddress = "192.168.0.245"; //IP address of network connected printer
$bc = "123456789012"; //Data to include in label data - this example is just text
$qty = "1";
$zpldata = "
^XA
^PW812
^FT0,260^A0N,260^FB812,1,0,C^FD" . $bc . "\&^FS
^PQ" . $qty . "
^XZ";

try {
    $fp=pfsockopen($zaddress,9100);
    fputs($fp,$zpldata);
    fclose($fp);
    $status="success";
    $zpl = $zpldata;
    $curl = curl_init();// print density 8dpmm=203dpi, 12dpmm=300dpi / width x height / index nth (0)
    curl_setopt($curl, CURLOPT_URL, "http://api.labelary.com/v1/printers/8dpmm/labels/4.0x6.0/0/"); //downloads a 4x6 label image at 203dpi
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $zpl);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: image/png"));
    $result = curl_exec($curl);
    if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) {
        $file = fopen("printerlabel.png", "w");
        fwrite($file, $result); //writes the png file to the server
        fclose($file);
    }else{print_r("Error: $result");}
    curl_close($curl);
    $qty = "";
    }catch (Exception $e) {echo "<div class='alert alert-danger'>Caught exception: ",  $e->getMessage(), "\n</div>";}
}
?>

Leave a Comment