PHP

What To Do When get_html_translation_table() And htmlspecialchars() Doesn't Work

I found a little problem today when processing a bit of text from a non-english site. I found that the text was being loaded properly, but because it was in UTF-8 encoding PHP couldn't use htmlspecialchars() or apply get_html_translation_table() to the string to properly encode the foreign characters. These methods just don't have any effect. This is because PHP (before version 5.2.x) doesn't natively support unicode character encoding and is therefore not able to translate characters in UTF-8 format.

To get around this just use the utf8_decode() function on the string to convert it into a usable format.

Work Out Size In Bytes Of A PHP String

I found this very handy function on the php.net site in the user comments for the strlen() function. It accepts a string in ASCII or UTF-8 format and finds out how long that string is in bytes.

The function works by going through the string and adding how many bytes each character represents. For normal ASCII values this is a single byte so 1 is added to the total. Unicode characters can be up to 6 bytes and so the rest of this function works out how many bytes the character takes up by using AND calculations.

Connect To FTP Server Using PHP

FTP connection functions have been built into PHP since version 4 and make transferring files through FTP very easy.

The main function involved is called ftp_connect() which takes a FTP host as a parameter and attempts to connect to it. The port and a timeout limit can also be added to the function if needed.

Once a connection has been made then the ftp_login() function is used to attempt a login. This function returns true on success and false if it fails. The following snippet of code will attempt to connect and login to an FTP server, if any step fails then the code will print out a message saying so.

String Equals Zero In PHP

Due to the weakly-typed nature of PHP you can do some odd things, some of which are good, and some of which will enable you to shoot yourself in the foot. Take the following little snippet.

echo '1' + 5;

In some languages this might cause the program to fall over, but PHP will try to evaluate any string into an integer. In this case it converts the string to an integer 1 and adds this to 5 to make 6.

As an aside, if you did this in JavaScript then you would find the opposite result. Because the concatenation character is the same as the addition character JavaScript will always try to truncate the value if any of the present values are a string. So the result in JavaScript would be "15".

If we change the string to a string of "one" and then did the same then the result is 5.

Using PHP To Split A String Into Characters

Use the following code to split a string into an array of characters.

$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

It uses the preg_split() PHP function which takes a number of parameters. These area as follows:

  1. The regular expression to be used. In this case it matches everything.
  2. The string to be used in the regular expression.
  3. This is the character limit. In this case -1 mean no limit, so the function will work for any size of string.
  4. The last parameter can be a flag or series of flags separated by the | character. In this case the PREG_SPLIT_NO_EMPTY flag is used. This prevents the function from returning any empty strings. So if your string has any spaces in it they will not be returned.

To give an example, take the following string variable.

PHP Function To Work Out Age From Date

Use the following function to work out how many years have passed since an event. This can be useful if you want to work out a persons age based on their birthday.

The function works by standardising the format of the date using the PHP strtotime() function. This is the first step of the function and sorts out if the date is valid or not. Once this has been done then the date is formatted into a standard form of yyyy-mm-dd, which is then split using the explode() function. The year of the inputted date is then subtracted from the current year, giving the age in years. A final check makes sure that the date hasn't passed yet, and subtracts one from the years value to give a more accurate result. Here is the function:

Installing XDebug On Windows

XDebug is an excellent debugging solution that will give you a more detailed indication of what is wrong in your code. Here is an example of trying to divide two variables that have a value of 0.

Using The e Modifier In PHP preg_replace

The PHP function preg_replace() has powerful functionality in its own right, but extra depth can be added with the inclusion of the e modifier. Take the following bit of code, which just picks out the letters of a string and replaces them with the letter X.

$something = 'df1gdf2gdf3sgdfg';
$something = preg_replace("/([a-z]*)/", "X", $something);
echo $something; // prints XX1XX2XX3XX

This is simple enough, but using the e modifier allows us to use PHP functions within the replace parameters. The following bit of code turns all letters upper case in a string of random letters by using the strtoupper() PHP function.

Swap Values Without A Third Variable In PHP

Swapping variable values is important in sorting algorithms when you want to swap a higher value with a lower one. The usual action of variable assignment is to take the first value, put the value of this variable in a temporary variable and then assign the value of the second variable to the first one. As in the following code:

$tmp = $a;
$a = $b;
$b = $tmp;

This can be rewritten using the bitwise Xor (exclusive or) operator.

$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;

This can also be written in the shorthand notation as follows:

$a ^= $b;
$b ^= $a;
$a ^= $b;

Convert A sitemap.xml File To A HTML Sitemap With PHP

I have already talked about converting a sitemap.xml file into a urllist.txt file, but what if you want to create a HTML sitemap? If you have a sitemap.xml file then you can use this to spider your site, scrape the contents of each page and populate the HTML file with this information.

The following code does this. For every page it looks for the title tag, the description meta tag and the first h2 tag on the page. These items are then used to construct a segment of HTML for that page.