linein designs

05 Jan, 2007

Convert ISBN10 to ISBN13 with PHP

Posted by: john In: php|programing

Since at the start of 2007 all books will no longer be using the ISBN10, we needed a way to convert all those ISBN10 numbers to the new ISBN13 (or EAN).


function genchksum13($isbn) {
    $isbn = trim($isbn);
    for ($i = 0; $i <= 12; $i++) {
        $tc = substr($isbn, -1, 1);
        $isbn = substr($isbn, 0, -1);
        $ta = ($tc*3);
        $tci = substr($isbn, -1, 1);
        $isbn = substr($isbn, 0, -1);
        $tb = $tb + $ta + $tci;
    }
    $tg = ($tb / 10);
    $tint = intval($tg);
    if ($tint == $tg) { return 0; }
    $ts = substr($tg, -1, 1);
    $tsum = (10 - $ts);
    return $tsum;
}
function isbn10_to_13($isbn) {
    $isbn = trim($isbn);
    if(strlen($isbn) == 12){ // if number is UPC just add zero
        $isbn13 = '0'.$isbn;}
    else
    {
        $isbn2 = substr("978" . trim($isbn), 0, -1);
        $sum13 = genchksum13($isbn2);
        $isbn13 = "$isbn2$sum13";
    }
    return ($isbn13);
}

// usage //

echo isbn10_to_13('1234567890'); // returns ISBN13

There are no checks in the code to see if the number is numeric for example, but this should give you a good place to start.

Similar Posts:

7 Comments »

 
Comment by PASH
 
Comment by Bob Zipoli
 
Comment by John

$tb is undefined at first. Should it be 0? or some other number

 
Comment by David


<?php

$isbn = '978' . substr($isbn10, 0, -1);

for ($i = 0; $i 0)
$checkDigit = 10 - $checkDigit;

$isbn .= $checkDigit;

echo('ISBN-13: ' . $isbn);

?>

 
Comment by Karunakar

Thank you very much. Works perfectly. You saved my time as i was going to write it myself. :) :)

 
Comment by Paul

This works great – Thank you!

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post


  • Seren: Thanks - google did not fail me in finding this snippet (after 2 hours of 'why isn't this working!' before I choose to look for answers. That select
  • zdenis: type your scp command with nohup at the beginning: >nohup scp... enter your password stop temporarily the command with CTRL+z put on b
  • Criz: php script >> How to get the number of hours and minutes of a two set of time like this sample. 1st set of time : 8:00 to 17:00 2nd set of


Please Support Our Friends

Banner
FreshBooks

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.