25
Thu, Apr
0 New Articles

Character Encoding with PHP

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

A conversion table is a very simple concept. In PHP, it's also very simple to implement.

 

Editor's note: This article is an excerpt from You Want to Do WHAT with PHP?, a new book from MC Press.

 

Computers know nothing about language. Actually, when you get right down to it, they know nothing of numbers either. All that computers know is on and off. They can change the ons and offs based on other ons and offs. If certain ons are on, the processor will do one thing; if they are off, it will do another. A computer is perfectly happy with this arrangement.

 

However, the purpose of a computer is to do work for a human. A computer is a machine whose purpose is to make a human's job easier (or enable a human to blow up zombies, for that matter). That means that the computer has a problem: it doesn't know how to talk to the human in its own language. For this reason, humans needed to teach computers how to talk with them.

 

In the early days, this task was quite simple. Given that computers were basically created in the English-speaking part of the world, English was a natural choice to provide the interface so that humans and computers could talk. However, if you were to read through some of the mainframe program calls, it would be apparent that some give and take took place in both directions; the commands that the humans gave the system are actually quite cryptic, unless you know the language.

 

The reason for this is the limitation of resources. In the early days of computing, every bit was sacred. Every bit was great. And so we started with what is called the American Standard Code for Information Interchange, or ASCII as we now know it. ASCII is a 7-bit code that gave developers more than enough room to handle the 26 characters of the English alphabet plus some punctuation, special characters, and control characters. All told, 127 options for managing data.

 

At its most basic level, a character set is a translation for the computer. It translates the numbers that the computer stores into graphical characters. A computer cannot store a letter, but it can store a numeric representation of that letter. The character set defines the standard of translation between the number and the graphical character.

 

For example, you cannot store the letter "A" on a computer. A computer doesn't really know numbers, and it really doesn't know letters. But numbers can have binary representations. You could also have a binary representation of a letter, but it would conflict with the binary representation of a number. Say you had the number 12 and you wanted to add 4 to it. Would that be the number 4 or the letter "d"?

 

So, a computer's primary method of communication is via numbers, and the character set is the mapping between the numbers, which the computer is able to work with, and the human. And thus the communication problem between computer and human is solved, right? Not exactly.

 

In the early days of computing, ASCII was not as prevalent as it is today. A competitor was Extended Binary Coded Decimal Interchange Code, or EBCDIC. Written on the IBM System/360, EBCDIC became quite common due to the popularity of that system.

 

With that (and other situations like it), character encoding issues arose. Why? Remember that a letter is just a certain number. In ASCII, the number for the letter "A" is 65. In EBCDIC, the number for the letter A is 193. Why the difference? I have heard from some IBM i (the IBM midrange integrated system) people that EBCDIC was good for punch cards because the way the bits were laid out made for more durable cards.

 

Before the Web-based whippersnappers (I count myself part of this crowd) go off on this, remember that modern computer science is a very new endeavor. The problems that people in the 1950s and 1960s had to solve were basically the same, but different limitations applied. The first commercially available microprocessor, the Intel 4004, was a 4-bit machine that debuted in 1971. Both ASCII and EBCDIC were available in 1963, eight years earlier. In other words, punch cards were a necessary step for us to get to the point where we are today.

 

But the problem of how to represent characters remains, and that is where character set conversion comes into play. Imagine that you have one system, an IBM mainframe, that started its life in the 1960s and has been upgraded through the years, first to a System/390 and then to a System i or System z. You may have some applications that continue to use EBCDIC, but you run on a computer that uses ASCII as its default character set, and you need to read from the older computer.

 

To illustrate the problem, let's take a look at what an EBCDIC-encoded "hello world" looks like. Figure 3.1 shows this PHP code.

 

$str = pack( 'CCCCCCCCCCC',

       0x88, 0x85, 0x93, 0x93, 0x96, 0x40, 0xa6, 0x96,

       0x99, 0x93, 0x84

);

 

echo $str;

Figure 3.1: EBCDIC-encoded character string

 

Remember that a character encoding is just a sequence of numbers, but each individual number represents an individual character. When we run the preceding code, we get something a little different from what we intended:

 

ˆ…""–@¦–™"„

 

The reason for this is simple. My browser understands ASCII, and according to ASCII, those are the characters I asked it to print out. To show this, let's change the code to its ASCII representation (Figure 3.2).

 

$str = pack( 'CCCCCCCCCCC',

       0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77,0x6f,

       0x72, 0x6c, 0x64

);

echo $str;

Figure 3.2: ASCII-encoded character string

 

The code looks the same, except with different numbers. But when we print it out in the browser, we get a different result:

 

hello world

 

The question, then, is how do we get something that was returned to us in EBCDIC to display properly on a browser that does not support it? You typically do this with some kind of character set conversion. All the character set conversion does is change the numbers in a string of one character set to the numbers in the string of the other character set that matches the letter. This is usually done using a conversion table.

 

A conversion table is a very simple concept. In PHP, it's also very simple to implement. You basically have a numerical array of all characters that are convertible, starting at zero. Then, for each numerical key of the array, you have the corresponding value in the other character set that represents the same letter. So, for example, in ASCII the ordinal for the letter "h" is 0x68, or 104. In EBCDIC, the letter "h" is 0x88 or 136. So, basically, the conversion table for EBCDIC to ASCII will have, at key number 136, the number 104.

 

Figure 3.3 shows an EBCDIC-to-ASCII character converter.

 

$table = array(

       0x00, 0x10, 0x20, 0x30, 0x00, 0x90, 0x00, 0x7f,

       0x00, 0x00, 0x00, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,

       0x10, 0x11, 0x12, 0x00, 0x00, 0x00, 0x80, 0x17,

       0x18, 0x19, 0x00, 0x00, 0x1c, 0x1d, 0x1e, 0x1f,

       0x00, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x16, 0x1b,

       0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x60, 0x70,

       0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x40,

       0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x00, 0x1a,

       0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x00, 0x5b, 0x2e, 0x3c, 0x28, 0x2b, 0x21,

       0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x00, 0x5d, 0x24, 0x2a, 0x29, 0x3b, 0x5e,

       0x2d, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x00, 0x7c, 0x2c, 0x25, 0x5f, 0x3e, 0x3f,

       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22,

       0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,

       0x68, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,

       0x71, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,

       0x79, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,

       0x48, 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,

       0x51, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x5c, 0x00, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,

       0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

       0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,

       0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

);

 

// EBCDIC "hello world"

$str = pack( 'CCCCCCCCCCC',

       0x88, 0x85, 0x93, 0x93, 0x96, 0x40, 0xa6, 0x96,

       0x99, 0x93, 0x84

 

);

 

$len = strlen($str);

$strBytes = array_values(

                    unpack(

                           'C*',

                           $str

                    )

);

for ($c = 0; $c < $len; $c++) {

       $str[$c] = pack(

                       'C',

                       $table[

                              $strBytes[$c]

                       ]

       );

}

 

echo $str;

Figure 3.3: EBCDIC-to-ASCII character converter

 

The first part of this code is the conversion table. It may look like just a series of bytes, but it is actually the numerically indexed array we noted earlier that matches the characters from one character set to another.

 

The first stage of the process is to extract the numerical values of the string. You could achieve this with repeated calls to the ord() function, but, in general, if you can do something in one call, you should. The $strBytes constant will contain all the individual byte values in our EBCDIC-encoded string.

 

The next step is just value replacement. Replace the value of $str[$c] with the table-corrected value. That's it. Now, when we run our code, we get the output we expect:

 

hello world

 

Our code is now complete. We have the mechanism for converting between any character set in the English language. So, we're all done, right? Nope. Clearly, there are other languages in the world. So, how do we handle many of them? Enter the eighth bit.

 

Most "Latin" character encodings support ASCII as part of their encoding. This is simply because large parts of most Western language alphabets use English characters, and the people who use these character sets will have a fair amount of contact with English-speaking people. For those two reasons, many of the Western world's character sets include the English ASCII component for the lower bits and then the language-specific characters in the upper values — those above character 127.

 

To see this in action, consider the script shown in Figure 3.4.

 

header(

       'Content-Type: text/plain; charset="'

       . $_GET['charset']

       . '"'

);

for ($c = 0; $c < 255; $c++) {

 

       if ($c % 16 == 1) echo "\n";

 

       $char = pack('C', $c);

       if (ctype_print($c)) {

             echo $char . ' ';

       } else {

             echo '  ';

       }

}

Figure 3.4: Demonstrating high-bit characters

 

What this code does is print the byte of each character from 0 to 254. However, you can tweak the character set via the query string. So, if we enter the URL print.php?charset=ISO-8859-1, we get the output shown in Figure 3.5.

 

011211KevinFig3-5

Figure 3.5 Output of high-bit characters with IS0-8859-1 encoding

 

If we enter the URL print.php?charset=ISO-8859-7, the same bytes are being printed, but we're telling the browser to use the ISO Greek character set to render those bytes (Figure 3.6).

 

011211KevinFig3-6

Figure 3.6: Output of high-bit characters with IS0-8859-7 encoding

 

If we enter print.php?charset=Windows-1255, we get the Hebrew characters (Figure 3.7).

 

011211KevinFig3-7 ?

Figure 3.7: Output of high-bit characters with Windows-1255 encoding

 

Again, nothing has changed in terms of the output between the individual URLs. Only the charset variable, as part of the header, has changed.

 

 


 

Kevin Schroeder

Kevin Schroeder has a memory TTL of 10 years, and so he has been working with PHP for longer than he can remember. He is a member of the Zend Certification Advisory Board and is a Magento Certified Developer Plus. He has spoken at numerous conferences, including ZendCon, where he was twice the MC. When his head isn’t in code (if code is poetry, then it is Vogon poetry), Kevin is writing music, having been a guitarist since hair bands were cool (and having survived their welcomed demise). He has recorded two albums, Coronal Loop Safari and Loudness Wars. Kevin’s wisdom is dispensed to his loyal followers on Twitter at @kpschrade and on his blog at www.eschrade.com, where he speaks in the first person.


MC Press books written by Kevin Schroeder available now on the MC Press Bookstore.

Advanced Guide to PHP on IBM i Advanced Guide to PHP on IBM i
Take your PHP knowledge to the next level with this indispensable guide.
List Price $79.95

Now On Sale

The IBM i Programmer’s Guide to PHP The IBM i Programmer’s Guide to PHP
Get to know the PHP programming language and how it can--and should--be deployed on IBM i.
List Price $79.95

Now On Sale

You Want to Do What with PHP? You Want to Do What with PHP?
This book for the creative and the curious explores what’s possible with PHP.
List Price $49.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: