May 072012
 

Here’s a basic script I made that uses PHP, cURL, and barcoding.com. It reads UPCs from csv files (or just a list) and sends a request to barcoding.com. Barcoding.com then returns an image with the barcode. Keep in mind barcoding.com is a free service and isn’t designed to be used in the way this script uses it, so please use it carefully.


<?php
$file = 'upcs.csv'; // Path to CSV file
$field = 0; //Column number of the UPC (0 if in the first column, 1 for the 2nd column, etc)
$output = 'C:\\upcs\\'; //Directory to save outputted UPCs to

$csvFile = fopen($file, "r"); //open the csv file for reading
while($data = fgetcsv($csvFile)) { //for each, add upc to array
if(strlen($data[$field]) === 12) { //prevent from adding data that isn't a 12 digit upc
$upcA[] = $data[$field];
}
}
fclose($csvFile);

function saveBarcode($url, $code) {
global $output;
$url = "http://www.barcoding.com".$url;
$ofile = "$output$code.png";
if(@$out = fopen($ofile, "x")) { // prevent problems when the file already exists
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FILE, $out);
curl_exec($ch);
curl_close($ch);
fclose($out);
}
}

function makeBarcode($code) { //generates barcode image from upc using barcoding.com
$url = "http://www.barcoding.com/upc/buildbarcode.asp?cpaint_function=BuildBarcode&cpaint_argument[]=$code&cpaint_argument[]=9&cpaint_argument[]=5&cpaint_response_type=TEXT";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$url = curl_exec($ch);
curl_close($ch);
saveBarcode($url, $code);
}

foreach($upcA as $upc) {
makeBarcode($upc);
}
?>

Share